UNPKG

3.5 kBJavaScriptView Raw
1const fs = require('fs'),
2 rollup = require('rollup'),
3 babel = require('maptalks-rollup-plugin-babel'),
4 commonjs = require('rollup-plugin-commonjs'),
5 localResolve = require('rollup-plugin-local-resolve'),
6 nodeResolve = require('rollup-plugin-node-resolve'),
7 uglify = require('uglify-js').minify,
8 zlib = require('zlib');
9
10module.exports = class BundleHelper {
11 constructor(pkg) {
12 this.pkg = pkg;
13 const year = new Date().getFullYear();
14 this.banner = `/*!\n * ${pkg.name} v${pkg.version}\n * LICENSE : ${pkg.license}\n * (c) 2016-${year} maptalks.org\n */`;
15 let outro = pkg.name + ' v' + pkg.version;
16 if (this.pkg !== 'maptalks') {
17 if (this.pkg.peerDependencies && this.pkg.peerDependencies['maptalks']) {
18 this.banner += `\n/*!\n * requires maptalks@${pkg.peerDependencies.maptalks} \n */`;
19 outro += `, requires maptalks@${pkg.peerDependencies.maptalks}.`;
20 }
21 }
22 this.outro = `typeof console !== 'undefined' && console.log('${outro}');`;
23 }
24
25 /**
26 * Generate the bundle using rollup
27 * @param {String} entry the entry file path, relative to the project root.
28 * @param {Object} [options=null] rollup's options
29 */
30 bundle(entry, options) {
31 const pkg = this.pkg;
32
33 options = options || this.getDefaultRollupConfig();
34 options.input = entry;
35
36 const umd = {
37 'extend' : true,
38 'sourcemap': false,
39 'format': 'umd',
40 'globals' : {
41 'maptalks' : 'maptalks'
42 },
43 'name': 'maptalks',
44 'banner': this.banner,
45 'file': 'dist/' + pkg.name + '.js',
46 'outro' : this.outro
47 };
48 const es = {
49 'sourcemap': false,
50 'format': 'es',
51 'globals' : {
52 'maptalks' : 'maptalks'
53 },
54 'banner': this.banner,
55 'file': 'dist/' + pkg.name + '.es.js',
56 'outro' : this.outro
57 };
58 return rollup.rollup(options).then(bundle => Promise.all(
59 [
60 bundle.write(umd),
61 bundle.write(es),
62 ]
63 ));
64 }
65
66 getDefaultRollupConfig() {
67 return {
68 'external': [
69 'maptalks'
70 ],
71 'plugins': [
72 localResolve(),
73 nodeResolve({
74 module: true,
75 jsnext: true,
76 main: true
77 }),
78 commonjs(),
79 babel({
80 plugins : ['transform-proto-to-assign']
81 })
82 ]
83 };
84 }
85
86 /**
87 * Minify the bundle and also generate a gzipped version.
88 * It assumes bundle is already at 'dist/pkgname.js'
89 */
90 minify() {
91 const name = this.pkg.name;
92 const dest = 'dist/' + name + '.js';
93 const code = fs.readFileSync(dest).toString('utf-8');
94 const u = uglify(code, {
95 'output': {
96 'ascii_only': true
97 }
98 });
99 const minified = this.banner + '\n' + u.code;
100 fs.writeFileSync('dist/' + name + '.min.js', minified);
101 const gzipped = zlib.gzipSync(minified);
102 fs.writeFileSync('dist/' + name + '.min.js.gz', gzipped);
103 }
104};