-
Notifications
You must be signed in to change notification settings - Fork 55
/
build.js
311 lines (259 loc) · 9.9 KB
/
build.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/* global BUILD_CONFIG, UglifyJS */
define(function (require) {
// var mangleString = require('./mangleString');
var saveAs = require('./lib/FileSaver');
var rollup = require('rollup');
var transformDev = require('transformDev');
var TOP_MODULE_NAME = 'topModuleInRequireES';
var RETRY_MAX = 2;
var TIMEOUT = 10000;
var RETRY_DELAY = 2000;
var $log = document.getElementById('log');
var version = BUILD_CONFIG.version + '';
var isVersion5 = version.startsWith('5');
var jsDelivrBase = 'https://cdn.jsdelivr.net/npm';
var urlArgs = '__v__=' + (+new Date());
var topCode = [`export * from "echarts/src/echarts";`];
var srcFolder = version.startsWith('5.0.0') ? 'esm' // Only 5.0.0 has esm folder
: isVersion5 ? 'lib' : 'src';
if (BUILD_CONFIG.api && (version.startsWith('5.0.0') || !isVersion5)) {
topCode.push(`export * from "echarts/src/export";`);
}
// Including charts
(BUILD_CONFIG.charts || '').split(',').forEach(function (chart) {
chart && topCode.push(`import "echarts/src/chart/${chart}";`);
});
if (topCode.indexOf(`echarts/src/chart/scatter`) >= 0) {
topCode.push(`import "echarts/src/chart/effectScatter"`);
}
// Including components
(BUILD_CONFIG.components || '').split(',').forEach(function (component) {
component && topCode.push(`import "echarts/src/component/${component}";`);
});
if (BUILD_CONFIG.vml && !isVersion5) {
topCode.push(`import "zrender/${srcFolder}/vml/vml";`);
}
if (BUILD_CONFIG.svg) {
topCode.push(`import "zrender/${srcFolder}/svg/svg";`);
}
// Always require log and time axis
topCode.push(
`import "echarts/src/scale/Time";`,
`import "echarts/src/scale/Log";`
);
var npmEntries = {};
var pathsConfig = {
'echarts/src': `/echarts@${version}/${srcFolder}`
};
function resolveNpmDependencies(pkg, version) {
return fetch(`${jsDelivrBase}/${pkg}@${version}/package.json`, { mode: 'cors' })
.then(response => response.json())
.then(pkgCfg => {
var entry = pkgCfg.module || pkgCfg.main || 'index.js';
if (!entry.endsWith('.js')) {
entry = entry + '.js';
}
npmEntries[pkg] = `/${pkg}@${version}/${entry}`;
var promises = [];
for (let pkgName in pkgCfg.dependencies) {
var depVersion = pkgCfg.dependencies[pkgName];
pathsConfig[pkgName] = `/${pkgName}@${depVersion}`;
promises.push(resolveNpmDependencies(pkgName, depVersion));
}
return Promise.all(promises);
});
}
resolveNpmDependencies('echarts', version)
.then(startRollup)
// Loading scripts and build
function startRollup() {
rollup.rollup({
input: TOP_MODULE_NAME,
legacy: true,
plugins: [{
resolveId: function (importee, importor) {
if (importee === TOP_MODULE_NAME) {
return importee;
}
// console.log('resolveid', importee, importor);
return getAbsolutePath(
importee,
importor !== TOP_MODULE_NAME ? importor : null
);
},
transform: function (code) {
return {
code: code.replace(/process.env.NODE_ENV/g, JSON.stringify(
!BUILD_CONFIG.source ? 'production' : 'development'
))
};
},
load: function (path) {
if (path === TOP_MODULE_NAME) {
return topCode.join('\n');
}
var retryCount = 0;
return new Promise(function (resolve, reject) {
function retryableLoad() {
// When using apache CDN, might fail to loading soource.
if (retryCount >= RETRY_MAX) {
var log = 'Loaded module failed: "' + path
+ '"<br><strong style="color:red">! Please reload page to retry. !</strong>';
builderLog(log);
return reject(log);
}
ajax(`${jsDelivrBase}/${path}`, TIMEOUT)
.then(function (content) {
builderLog('Loaded module: "' + path + '"');
resolve(content);
})
.catch(function () {
retryCount++;
setTimeout(retryableLoad, RETRY_DELAY);
});
}
retryableLoad();
});
}
}]
}).then(function (bundle) {
return bundle.generate({
name: 'echarts',
format: 'umd',
legacy: true
});
}).then(function (result) {
var code = result.code;
code = transformDev.transform(code, false, !BUILD_CONFIG.source ? 'false' : 'true').code;
if (!BUILD_CONFIG.source) {
builderLog('<br />Compressing code...');
// code = mangleString(code);
// Otherwise uglify will throw error.
code = code.replace(/\t/g, ' ');
code = jsCompress(code);
}
download(code);
builderLog('<br />Completed');
document.getElementById('tip').innerHTML = 'OK';
});
}
function download(code) {
try {
var blob = new Blob([code], {
type: 'text/plain;charset=utf8'
});
// var URL = window.URL || window.webkitURL;
// var scriptUrl = URL.createObjectURL(blob);
// URL.revokeObjectURL(blob);
// window.open(scriptUrl);
// return;
var fileName = ['echarts'];
if (!BUILD_CONFIG.source) {
fileName.push('min');
}
fileName.push('js');
saveAs(blob, fileName.join('.'));
}
catch (e) {
console.error(e);
window.open('data:text/plain;charset=utf-8,' + encodeURIComponent(code));
}
}
function builderLog(msg) {
$log.innerHTML += msg + '<br />';
$log.scrollTop = $log.scrollHeight;
}
function jsCompress(source) {
var ast = UglifyJS.parse(source);
/* jshint camelcase: false */
// compressor needs figure_out_scope too
ast.figure_out_scope();
ast = ast.transform(UglifyJS.Compressor());
// need to figure out scope again so mangler works optimally
ast.figure_out_scope();
ast.compute_char_frequency();
ast.mangle_names();
return ast.print_to_string();
}
// Get absolute path. `basePath` can be omitted if moduleId is absolute.
function getAbsolutePath(moduleId, basePath) {
if (npmEntries[moduleId]) {
return npmEntries[moduleId];
}
moduleId = addExt(moduleId);
for (var path in pathsConfig) {
if (pathsConfig.hasOwnProperty(path)) {
if (moduleId.indexOf(path) === 0) {
return moduleId.replace(path, pathsConfig[path]);
}
}
}
if (basePath) {
moduleId = resolve(dir(basePath), moduleId);
}
if (moduleId.charAt(0) !== '/') {
throw new Error('"' + moduleId + '" can not be found.');
}
return moduleId;
}
function addExt(moduleId) {
if (moduleId.split('/').pop().indexOf('.') < 0) {
moduleId += '.js';
}
return moduleId;
}
function ajax(toUrl, timeout) {
toUrl += '?' + urlArgs;
return fetch(toUrl, {
mode: 'cors'
}).then(response => response.text());
}
// Nodejs `path.resolve`.
function resolve() {
var resolvedPath = '';
var resolvedAbsolute;
for (var i = arguments.length - 1; i >= 0 && !resolvedAbsolute; i--) {
var path = arguments[i];
if (path) {
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path[0] === '/';
}
}
if (!resolvedAbsolute) {
throw new Error('At least one absolute path should be input.');
}
// Normalize the path
resolvedPath = normalizePathArray(resolvedPath.split('/'), false).join('/');
return '/' + resolvedPath;
}
// resolves . and .. elements in a path array with directory names there
// must be no slashes or device names (c:\) in the array
// (so also no leading and trailing slashes - it does not distinguish
// relative and absolute paths)
function normalizePathArray(parts, allowAboveRoot) {
var res = [];
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// ignore empty parts
if (!p || p === '.') {
continue;
}
if (p === '..') {
if (res.length && res[res.length - 1] !== '..') {
res.pop();
}
else if (allowAboveRoot) {
res.push('..');
}
} else {
res.push(p);
}
}
return res;
}
function dir(path) {
if (path) {
return path.charAt(path.length - 1) === '/' ? path : resolve(path, '..');
}
}
});