@doracli/rollup 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,909 @@
1
+ import { isArray, isString, isObject } from '@cclr/lang';
2
+ import { isValidDir, getNodeModulesDir, getDirname, getCwd, isValidFilePathSync, mkdirRecursive, getFilename } from '@dorabag/file-pro';
3
+ import { findInput, cLog, getTsPathAlias, picocolors } from '@doracli/helper';
4
+ import { join, isAbsolute, resolve, relative, dirname } from 'path';
5
+ import alias from '@rollup/plugin-alias';
6
+ import babel from '@rollup/plugin-babel';
7
+ import commonjs from '@rollup/plugin-commonjs';
8
+ import copy from 'rollup-plugin-copy';
9
+ import { dts } from 'rollup-plugin-dts';
10
+ import json from '@rollup/plugin-json';
11
+ import terser from '@rollup/plugin-terser';
12
+ import autoprefixer from 'autoprefixer';
13
+ import cssnanoPlugin from 'cssnano';
14
+ import { rmSync } from 'fs';
15
+ import { writeFile } from 'fs/promises';
16
+ import postcss from 'rollup-plugin-postcss';
17
+ import resolve$1 from '@rollup/plugin-node-resolve';
18
+ import { nodeBabelPreset, reactBabelPreset } from '@doracli/preset-babel';
19
+ import { rollup, watch } from 'rollup';
20
+
21
+ function _arrayLikeToArray(r, a) {
22
+ (null == a || a > r.length) && (a = r.length);
23
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
24
+ return n;
25
+ }
26
+ function _arrayWithoutHoles(r) {
27
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
28
+ }
29
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
30
+ try {
31
+ var i = n[a](c),
32
+ u = i.value;
33
+ } catch (n) {
34
+ return void e(n);
35
+ }
36
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
37
+ }
38
+ function _asyncToGenerator(n) {
39
+ return function () {
40
+ var t = this,
41
+ e = arguments;
42
+ return new Promise(function (r, o) {
43
+ var a = n.apply(t, e);
44
+ function _next(n) {
45
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
46
+ }
47
+ function _throw(n) {
48
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
49
+ }
50
+ _next(void 0);
51
+ });
52
+ };
53
+ }
54
+ function _classCallCheck(a, n) {
55
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
56
+ }
57
+ function _defineProperties(e, r) {
58
+ for (var t = 0; t < r.length; t++) {
59
+ var o = r[t];
60
+ o.enumerable = o.enumerable || false, o.configurable = true, "value" in o && (o.writable = true), Object.defineProperty(e, _toPropertyKey(o.key), o);
61
+ }
62
+ }
63
+ function _createClass(e, r, t) {
64
+ return r && _defineProperties(e.prototype, r), Object.defineProperty(e, "prototype", {
65
+ writable: false
66
+ }), e;
67
+ }
68
+ function _defineProperty(e, r, t) {
69
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
70
+ value: t,
71
+ enumerable: true,
72
+ configurable: true,
73
+ writable: true
74
+ }) : e[r] = t, e;
75
+ }
76
+ function _iterableToArray(r) {
77
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
78
+ }
79
+ function _nonIterableSpread() {
80
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
81
+ }
82
+ function ownKeys(e, r) {
83
+ var t = Object.keys(e);
84
+ if (Object.getOwnPropertySymbols) {
85
+ var o = Object.getOwnPropertySymbols(e);
86
+ r && (o = o.filter(function (r) {
87
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
88
+ })), t.push.apply(t, o);
89
+ }
90
+ return t;
91
+ }
92
+ function _objectSpread2(e) {
93
+ for (var r = 1; r < arguments.length; r++) {
94
+ var t = null != arguments[r] ? arguments[r] : {};
95
+ r % 2 ? ownKeys(Object(t), true).forEach(function (r) {
96
+ _defineProperty(e, r, t[r]);
97
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
98
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
99
+ });
100
+ }
101
+ return e;
102
+ }
103
+ function _objectWithoutProperties(e, t) {
104
+ if (null == e) return {};
105
+ var o,
106
+ r,
107
+ i = _objectWithoutPropertiesLoose(e, t);
108
+ if (Object.getOwnPropertySymbols) {
109
+ var n = Object.getOwnPropertySymbols(e);
110
+ for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
111
+ }
112
+ return i;
113
+ }
114
+ function _objectWithoutPropertiesLoose(r, e) {
115
+ if (null == r) return {};
116
+ var t = {};
117
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
118
+ if (-1 !== e.indexOf(n)) continue;
119
+ t[n] = r[n];
120
+ }
121
+ return t;
122
+ }
123
+ function _regenerator() {
124
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
125
+ var e,
126
+ t,
127
+ r = "function" == typeof Symbol ? Symbol : {},
128
+ n = r.iterator || "@@iterator",
129
+ o = r.toStringTag || "@@toStringTag";
130
+ function i(r, n, o, i) {
131
+ var c = n && n.prototype instanceof Generator ? n : Generator,
132
+ u = Object.create(c.prototype);
133
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
134
+ var i,
135
+ c,
136
+ u,
137
+ f = 0,
138
+ p = o || [],
139
+ y = false,
140
+ G = {
141
+ p: 0,
142
+ n: 0,
143
+ v: e,
144
+ a: d,
145
+ f: d.bind(e, 4),
146
+ d: function (t, r) {
147
+ return i = t, c = 0, u = e, G.n = r, a;
148
+ }
149
+ };
150
+ function d(r, n) {
151
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
152
+ var o,
153
+ i = p[t],
154
+ d = G.p,
155
+ l = i[2];
156
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
157
+ }
158
+ if (o || r > 1) return a;
159
+ throw y = true, n;
160
+ }
161
+ return function (o, p, l) {
162
+ if (f > 1) throw TypeError("Generator is already running");
163
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
164
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
165
+ try {
166
+ if (f = 2, i) {
167
+ if (c || (o = "next"), t = i[o]) {
168
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
169
+ if (!t.done) return t;
170
+ u = t.value, c < 2 && (c = 0);
171
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
172
+ i = e;
173
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
174
+ } catch (t) {
175
+ i = e, c = 1, u = t;
176
+ } finally {
177
+ f = 1;
178
+ }
179
+ }
180
+ return {
181
+ value: t,
182
+ done: y
183
+ };
184
+ };
185
+ }(r, o, i), true), u;
186
+ }
187
+ var a = {};
188
+ function Generator() {}
189
+ function GeneratorFunction() {}
190
+ function GeneratorFunctionPrototype() {}
191
+ t = Object.getPrototypeOf;
192
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
193
+ return this;
194
+ }), t),
195
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
196
+ function f(e) {
197
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
198
+ }
199
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
200
+ return this;
201
+ }), _regeneratorDefine(u, "toString", function () {
202
+ return "[object Generator]";
203
+ }), (_regenerator = function () {
204
+ return {
205
+ w: i,
206
+ m: f
207
+ };
208
+ })();
209
+ }
210
+ function _regeneratorDefine(e, r, n, t) {
211
+ var i = Object.defineProperty;
212
+ try {
213
+ i({}, "", {});
214
+ } catch (e) {
215
+ i = 0;
216
+ }
217
+ _regeneratorDefine = function (e, r, n, t) {
218
+ function o(r, n) {
219
+ _regeneratorDefine(e, r, function (e) {
220
+ return this._invoke(r, n, e);
221
+ });
222
+ }
223
+ r ? i ? i(e, r, {
224
+ value: n,
225
+ enumerable: !t,
226
+ configurable: !t,
227
+ writable: !t
228
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
229
+ }, _regeneratorDefine(e, r, n, t);
230
+ }
231
+ function _toConsumableArray(r) {
232
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
233
+ }
234
+ function _toPrimitive(t, r) {
235
+ if ("object" != typeof t || !t) return t;
236
+ var e = t[Symbol.toPrimitive];
237
+ if (void 0 !== e) {
238
+ var i = e.call(t, r);
239
+ if ("object" != typeof i) return i;
240
+ throw new TypeError("@@toPrimitive must return a primitive value.");
241
+ }
242
+ return ("string" === r ? String : Number)(t);
243
+ }
244
+ function _toPropertyKey(t) {
245
+ var i = _toPrimitive(t, "string");
246
+ return "symbol" == typeof i ? i : i + "";
247
+ }
248
+ function _unsupportedIterableToArray(r, a) {
249
+ if (r) {
250
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
251
+ var t = {}.toString.call(r).slice(8, -1);
252
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
253
+ }
254
+ }
255
+
256
+ /**
257
+ * 获取external配置
258
+ * @param envParams 环境参数
259
+ * @param options 用户配置的external选项
260
+ * @returns TExternalOption
261
+ */
262
+ var getExternal = function getExternal(_envParams, options) {
263
+ var _ref = options || {},
264
+ dependencies = _ref.dependencies,
265
+ devDependencies = _ref.devDependencies,
266
+ peerDependencies = _ref.peerDependencies,
267
+ externals = _ref.externals,
268
+ internals = _ref.internals,
269
+ filter = _ref.filter;
270
+ if (filter) return filter;
271
+
272
+ // 需要打包的模块
273
+ var internalsMap = isArray(internals) ? internals.reduce(function (prev, cur) {
274
+ prev[cur] = cur;
275
+ return prev;
276
+ }, {}) : internals || {};
277
+
278
+ // 不需要打包的模块
279
+ var extraExternals = isArray(externals) ? externals : Object.keys(externals || {});
280
+ var obj = _objectSpread2(_objectSpread2(_objectSpread2({}, dependencies), peerDependencies), devDependencies);
281
+ var externalList = Object.keys(obj).concat(extraExternals).filter(function (key) {
282
+ return !internalsMap[key];
283
+ });
284
+ return function (source, _importer, _isResolved) {
285
+ if (/^@doracli\//.test(source)) return true;
286
+ var isExternal = externalList.find(function (externalModule) {
287
+ return source.startsWith(externalModule);
288
+ });
289
+ return !!isExternal;
290
+ };
291
+ };
292
+
293
+ /**
294
+ * 获取入口文件
295
+ * @description input 不传,则自动寻找
296
+ * @param envParams 环境参数
297
+ * @param input 入口文件路径
298
+ * @returnscj
299
+ */
300
+ var getInput = /*#__PURE__*/function () {
301
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(envParams, input) {
302
+ var workRootDir, rightFile;
303
+ return _regenerator().w(function (_context) {
304
+ while (1) switch (_context.n) {
305
+ case 0:
306
+ workRootDir = envParams.workRootDir;
307
+ rightFile = input;
308
+ if (!isString(input)) {
309
+ _context.n = 2;
310
+ break;
311
+ }
312
+ _context.n = 1;
313
+ return isValidDir(input);
314
+ case 1:
315
+ if (_context.v) {
316
+ _context.n = 2;
317
+ break;
318
+ }
319
+ cLog.warn('rollup', 'input', "\u65E0\u6709\u6548\u5165\u53E3\u8DEF\u5F84 ".concat(input, "\uFF0C\u5C06\u81EA\u52A8\u5BFB\u627E\u6709\u6548\u8DEF\u5F84"));
320
+ rightFile = undefined;
321
+ case 2:
322
+ if (!rightFile) {
323
+ rightFile = findInput(workRootDir);
324
+ }
325
+ if (!rightFile) {
326
+ cLog.error('common', 'find_input', '需要有一个入口文件 index 或者 src/index');
327
+ process.exit();
328
+ }
329
+ cLog.log('rollup', 'input', "\u5165\u53E3\u6587\u4EF6\u8DEF\u5F84 ".concat(rightFile));
330
+ return _context.a(2, rightFile);
331
+ }
332
+ }, _callee);
333
+ }));
334
+ return function getInput(_x, _x2) {
335
+ return _ref.apply(this, arguments);
336
+ };
337
+ }();
338
+
339
+ var _excluded$3 = ["format"];
340
+ /**
341
+ * 生成单个output
342
+ * @description 如果不配置output,则默认生成cjs格式的output,输出路径为`lib/index.js`
343
+ * @description 自动组合完整的file
344
+ * @param optionsOutput
345
+ * @returns
346
+ */
347
+ var getOutput = function getOutput(envParams, options) {
348
+ var workRootDir = envParams.workRootDir;
349
+ if (!options) {
350
+ return {
351
+ file: join(workRootDir, 'lib/index.js'),
352
+ format: 'esm',
353
+ sourcemap: false
354
+ };
355
+ }
356
+ var format = options.format,
357
+ outputOptions = _objectWithoutProperties(options, _excluded$3);
358
+ var realFormat = format || 'esm';
359
+ return _objectSpread2({
360
+ format: realFormat,
361
+ sourcemap: false
362
+ }, outputOptions);
363
+ };
364
+
365
+ var _excluded$2 = ["entries"];
366
+
367
+ /**
368
+ * 获取别名插件
369
+ * @param config 快捷配置
370
+ * @param pluginConfig 标准配置
371
+ * @returns 别名插件
372
+ */
373
+ var getAliasPlugin = function getAliasPlugin(config, pluginConfig) {
374
+ var userConfig = config.alias,
375
+ tsConfigPath = config.tsConfigPath;
376
+ var aliasObj = getTsPathAlias(tsConfigPath || []);
377
+ var _ref = pluginConfig || {},
378
+ entries = _ref.entries,
379
+ extPluginConfig = _objectWithoutProperties(_ref, _excluded$2);
380
+ return alias(_objectSpread2(_objectSpread2({}, extPluginConfig), {}, {
381
+ entries: _objectSpread2(_objectSpread2(_objectSpread2({}, entries), userConfig), aliasObj)
382
+ }));
383
+ };
384
+
385
+ /**
386
+ * 获取Babel插件
387
+ * @param _config 快捷配置
388
+ * @param pluginConfig 标准配置
389
+ * @returns Babel插件
390
+ */
391
+ var getBabelPlugin = function getBabelPlugin(_config, pluginConfig) {
392
+ return babel(_objectSpread2({
393
+ babelrc: false,
394
+ configFile: false,
395
+ compact: false,
396
+ cwd: getNodeModulesDir(getDirname(import.meta)),
397
+ extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs'],
398
+ ignore: ['node_modules/**'],
399
+ babelHelpers: 'bundled',
400
+ exclude: 'node_modules/**'
401
+ }, pluginConfig));
402
+ };
403
+
404
+ /**
405
+ * 获取CommonJS插件
406
+ * @description 将 CommonJS 转换成 ES2015 模块供 Rollup 处理
407
+ * @param _config
408
+ * @param pluginConfig
409
+ * @returns
410
+ */
411
+ var getCommonjsPlugin = function getCommonjsPlugin(_config, pluginConfig) {
412
+ return commonjs(pluginConfig);
413
+ };
414
+
415
+ var _excluded$1 = ["targets"];
416
+ /**
417
+ * 获取拷贝插件
418
+ * @param config 快捷配置
419
+ * @param pluginConfig 标准配置
420
+ * @returns 拷贝插件
421
+ */
422
+ var getCopyPlugin = function getCopyPlugin(config, pluginConfig) {
423
+ var _ref = config || {},
424
+ copyList = _ref.copyList;
425
+ var _ref2 = pluginConfig || {},
426
+ targets = _ref2.targets,
427
+ extPluginConfig = _objectWithoutProperties(_ref2, _excluded$1);
428
+ var resTargets = _toConsumableArray(targets || []);
429
+ if (copyList) {
430
+ resTargets.push.apply(resTargets, _toConsumableArray(copyList));
431
+ }
432
+ return copy(_objectSpread2(_objectSpread2({}, extPluginConfig), {}, {
433
+ targets: resTargets
434
+ }));
435
+ };
436
+
437
+ /**
438
+ * 获取 dts 插件
439
+ * @param _config
440
+ * @param pluginConfig
441
+ * @returns
442
+ */
443
+ var getDtsPlugin = function getDtsPlugin(_config, pluginConfig) {
444
+ return dts(_objectSpread2({
445
+ respectExternal: false,
446
+ tsconfig: 'tsconfig.json',
447
+ compilerOptions: {}
448
+ }, pluginConfig));
449
+ };
450
+
451
+ /**
452
+ * 获取Json插件
453
+ * @description 允许将 .json 文件作为 ES6 模块导入
454
+ * @param _config
455
+ * @param pluginConfig
456
+ * @returns
457
+ */
458
+ var getJsonPlugin = function getJsonPlugin(_config, pluginConfig) {
459
+ return json(pluginConfig);
460
+ };
461
+
462
+ /**
463
+ * 获取代码压缩插件
464
+ * @returns Minimize插件
465
+ */
466
+ var getMinimizePlugin = function getMinimizePlugin() {
467
+ return terser();
468
+ };
469
+
470
+ var _excluded = ["plugins"];
471
+
472
+ /**
473
+ * 创建Postcss插件
474
+ * @param config 快捷配置
475
+ * @param pluginConfig 标准配置
476
+ * @returns Postcss插件
477
+ */
478
+ var getPostcssPlugin = function getPostcssPlugin(config, pluginConfig) {
479
+ var minimize = config.minimize,
480
+ output = config.output;
481
+ var _ref = pluginConfig || {},
482
+ injectPlugin = _ref.plugins,
483
+ otherConfig = _objectWithoutProperties(_ref, _excluded);
484
+ var outputWhole = isAbsolute(output) ? output : resolve(process.cwd(), output);
485
+ var plugins = [autoprefixer({
486
+ overrideBrowserslist: ['defaults', 'not ie < 8', 'last 2 versions', '> 1%', 'iOS 7', 'last 3 iOS versions']
487
+ })].concat(_toConsumableArray(injectPlugin || []));
488
+ if (minimize) {
489
+ plugins.push(cssnanoPlugin());
490
+ }
491
+
492
+ /**
493
+ * 输出文件锁,防止多次写入
494
+ * 当输出n个格式时,会被同时调用n次
495
+ */
496
+ var codeFileNameLock = '';
497
+ return postcss(_objectSpread2({
498
+ plugins: plugins,
499
+ extract: true,
500
+ onExtract: function () {
501
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(getExtracted) {
502
+ var _ref3, code, codeFileName, dir;
503
+ return _regenerator().w(function (_context) {
504
+ while (1) switch (_context.n) {
505
+ case 0:
506
+ _ref3 = getExtracted(), code = _ref3.code, codeFileName = _ref3.codeFileName;
507
+ if (!(codeFileNameLock === codeFileName)) {
508
+ _context.n = 1;
509
+ break;
510
+ }
511
+ return _context.a(2, false);
512
+ case 1:
513
+ codeFileNameLock = codeFileName;
514
+ if (isValidFilePathSync(outputWhole)) {
515
+ rmSync(outputWhole, {
516
+ recursive: true,
517
+ force: true
518
+ });
519
+ }
520
+ dir = dirname(outputWhole);
521
+ _context.n = 2;
522
+ return mkdirRecursive(dir);
523
+ case 2:
524
+ _context.n = 3;
525
+ return writeFile(outputWhole, code);
526
+ case 3:
527
+ cLog.info('style', 'success', "\u8F93\u51FA\u7C7B\u578B => css\uFF1B", "\u8DEF\u5F84 =>".concat(relative(getCwd(), outputWhole)));
528
+ codeFileNameLock = '';
529
+ return _context.a(2, false);
530
+ }
531
+ }, _callee);
532
+ }));
533
+ return function onExtract(_x) {
534
+ return _ref2.apply(this, arguments);
535
+ };
536
+ }()
537
+ }, otherConfig));
538
+ };
539
+
540
+ /**
541
+ * 获取解析插件
542
+ * @param config 快捷配置
543
+ * @param pluginConfig 标准配置
544
+ * @returns 解析插件
545
+ */
546
+ var getResolvePlugin = function getResolvePlugin(config, pluginConfig) {
547
+ var extensions = config.extensions;
548
+ return resolve$1(_objectSpread2({
549
+ extensions: extensions,
550
+ preferBuiltins: true
551
+ }, pluginConfig));
552
+ };
553
+
554
+ /**
555
+ * 获取Node环境下的插件集合
556
+ * @param config 快捷配置
557
+ * @returns
558
+ */
559
+ var getNodePlugins = function getNodePlugins(config) {
560
+ var alias = config.alias,
561
+ minimize = config.minimize;
562
+ config.copyMap;
563
+ var plugins = [getResolvePlugin({
564
+ extensions: ['.js', '.ts', '.json']
565
+ }, {
566
+ preferBuiltins: true
567
+ }), getAliasPlugin({
568
+ alias: _objectSpread2({
569
+ '@': 'src'
570
+ }, alias)
571
+ }), getCopyPlugin({
572
+ }), getCommonjsPlugin(), getJsonPlugin()];
573
+ plugins.push(getBabelPlugin({
574
+ }, nodeBabelPreset()));
575
+ if (minimize) {
576
+ plugins.push(getMinimizePlugin());
577
+ }
578
+ return plugins;
579
+ };
580
+
581
+ /**
582
+ * 获取Node环境下的插件集合
583
+ * @param config 快捷配置
584
+ * @returns
585
+ */
586
+ var getReactPlugins = /*#__PURE__*/function () {
587
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config) {
588
+ var alias, minimize, cssOutput, copy, plugins, _t, _t2, _t3, _t4, _t5, _t6;
589
+ return _regenerator().w(function (_context) {
590
+ while (1) switch (_context.n) {
591
+ case 0:
592
+ alias = config.alias, minimize = config.minimize, cssOutput = config.cssOutput, copy = config.copy;
593
+ _context.n = 1;
594
+ return getPostcssPlugin({
595
+ minimize: !!minimize,
596
+ output: cssOutput || 'lib/css/index.css'
597
+ });
598
+ case 1:
599
+ _t = _context.v;
600
+ _t2 = getResolvePlugin({
601
+ extensions: ['.ts', '.tsx', '.js', '.jsx', '.json', '.mjs']
602
+ }, {
603
+ preferBuiltins: true
604
+ });
605
+ _t3 = getAliasPlugin({
606
+ alias: _objectSpread2({
607
+ '@': 'src'
608
+ }, alias)
609
+ });
610
+ _t4 = getCopyPlugin({
611
+ copyList: copy
612
+ });
613
+ _t5 = getCommonjsPlugin();
614
+ _t6 = getJsonPlugin();
615
+ plugins = [_t, _t2, _t3, _t4, _t5, _t6];
616
+ plugins.push(getBabelPlugin({
617
+ }, reactBabelPreset()));
618
+ if (minimize) {
619
+ plugins.push(getMinimizePlugin());
620
+ }
621
+ return _context.a(2, plugins);
622
+ }
623
+ }, _callee);
624
+ }));
625
+ return function getReactPlugins(_x) {
626
+ return _ref.apply(this, arguments);
627
+ };
628
+ }();
629
+
630
+ /**
631
+ * 获取watch配置
632
+ * @param options
633
+ * @returns
634
+ */
635
+ var getWatch = function getWatch(envParams, options) {
636
+ var workRootDir = envParams.workRootDir;
637
+ return _objectSpread2({
638
+ exclude: 'node_modules/**',
639
+ include: join(workRootDir, 'src/**'),
640
+ clearScreen: false,
641
+ skipWrite: false,
642
+ buildDelay: 500,
643
+ chokidar: {
644
+ usePolling: true
645
+ }
646
+ }, options);
647
+ };
648
+
649
+ /**
650
+ * Create a Rollup build with the given options.
651
+ * @param options RollupOptions
652
+ * @returns
653
+ */
654
+ var createRollupBuild = function createRollupBuild(options) {
655
+ return rollup(options);
656
+ };
657
+
658
+ var Ctx = /*#__PURE__*/function () {
659
+ function Ctx(configCtx) {
660
+ _classCallCheck(this, Ctx);
661
+ _defineProperty(this, "configCtx", void 0);
662
+ _defineProperty(this, "rollupOptions", {});
663
+ _defineProperty(this, "rollupOutputList", []);
664
+ _defineProperty(this, "envParams", {
665
+ action: 'build',
666
+ workRootDir: getCwd()
667
+ });
668
+ this.configCtx = configCtx;
669
+ }
670
+ return _createClass(Ctx, [{
671
+ key: "updateEnvParams",
672
+ value: function updateEnvParams(argv) {
673
+ this.envParams = _objectSpread2(_objectSpread2({}, this.envParams), argv);
674
+ }
675
+ }, {
676
+ key: "updateRollupOptions",
677
+ value: function updateRollupOptions(options) {
678
+ this.rollupOptions = _objectSpread2(_objectSpread2({}, this.rollupOptions), options);
679
+ }
680
+ }, {
681
+ key: "updateRollupOutputList",
682
+ value: function updateRollupOutputList(list) {
683
+ var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
684
+ if (force) {
685
+ this.rollupOutputList = list;
686
+ } else {
687
+ this.rollupOutputList = [].concat(_toConsumableArray(this.rollupOutputList), _toConsumableArray(list));
688
+ }
689
+ }
690
+ }, {
691
+ key: "getDoraConfig",
692
+ value: function getDoraConfig() {
693
+ return this.configCtx.getDoraConfig();
694
+ }
695
+ }, {
696
+ key: "geTDoraConfigRollup",
697
+ value: function geTDoraConfigRollup() {
698
+ return this.configCtx.getDoraConfig().rollupConfig || {};
699
+ }
700
+ }]);
701
+ }();
702
+
703
+ /**
704
+ * Get a function to write the Rollup bundle with the given output options.
705
+ * @param rollupBuild RollupBuild
706
+ * @returns function that takes output options and writes the bundle
707
+ */
708
+ var getRollupWrite = function getRollupWrite(rollupBuild) {
709
+ return function (output) {
710
+ return rollupBuild.write(output);
711
+ };
712
+ };
713
+
714
+ /**
715
+ * 打包ts
716
+ * @param config 配置
717
+ */
718
+ var dealDts = /*#__PURE__*/function () {
719
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(config) {
720
+ var input, output, dtsBuild, _t;
721
+ return _regenerator().w(function (_context) {
722
+ while (1) switch (_context.p = _context.n) {
723
+ case 0:
724
+ input = config.input, output = config.output;
725
+ _context.p = 1;
726
+ _context.n = 2;
727
+ return createRollupBuild({
728
+ input: input,
729
+ external: function external(id) {
730
+ if (/\.(css|less|scss|sass|styl|png|jpe?g|svg|gif|webp|ico)$/.test(id)) {
731
+ return true;
732
+ }
733
+ return false;
734
+ },
735
+ plugins: [getResolvePlugin({
736
+ extensions: ['.ts']
737
+ }, {
738
+ preferBuiltins: true
739
+ }), getDtsPlugin()]
740
+ });
741
+ case 2:
742
+ dtsBuild = _context.v;
743
+ _context.n = 3;
744
+ return getRollupWrite(dtsBuild)({
745
+ file: output
746
+ });
747
+ case 3:
748
+ _context.n = 5;
749
+ break;
750
+ case 4:
751
+ _context.p = 4;
752
+ _t = _context.v;
753
+ cLog.error('dts ', 'dts_error', 'dts构建捕获到错误');
754
+ console.log(_t);
755
+ throw new Error(_t);
756
+ case 5:
757
+ return _context.a(2);
758
+ }
759
+ }, _callee, null, [[1, 4]]);
760
+ }));
761
+ return function dealDts(_x) {
762
+ return _ref.apply(this, arguments);
763
+ };
764
+ }();
765
+
766
+ /**
767
+ * 从rollup配置中,获取第一个input
768
+ * @param inputOrigin
769
+ * @returns
770
+ */
771
+ var getFirstInput = function getFirstInput(inputOrigin) {
772
+ if (typeof inputOrigin === 'string') {
773
+ var name = getFilename(inputOrigin);
774
+ return {
775
+ path: inputOrigin,
776
+ name: name
777
+ };
778
+ } else if (Array.isArray(inputOrigin) && inputOrigin.length > 0) {
779
+ var firstInput = inputOrigin[0];
780
+ var _name = getFilename(firstInput);
781
+ return {
782
+ path: firstInput,
783
+ name: _name
784
+ };
785
+ } else if (isObject(inputOrigin)) {
786
+ var firstKey = Object.keys(inputOrigin)[0];
787
+ var _firstInput = inputOrigin[firstKey];
788
+ return {
789
+ path: _firstInput,
790
+ name: firstKey
791
+ };
792
+ }
793
+ return undefined;
794
+ };
795
+
796
+ var rollupWatchLog = function rollupWatchLog(watcher) {
797
+ // event.code 可以是以下之一:
798
+ // START - 监视器正在(重新)启动
799
+ // BUNDLE_START - 单次打包
800
+ // * 如果存在,event.input 将是输入选项对象
801
+ // * event.output 包含生成的输出的 "file"
802
+ // 或 "dir" 选项值的数组
803
+ // BUNDLE_END - 完成打包
804
+ // * 如果存在,event.input 将是输入选项对象
805
+ // * event.output 包含生成的输出的 "file"
806
+ // 或 "dir" 选项值的数组
807
+ // * event.duration 是构建持续时间(以毫秒为单位)
808
+ // * event.result 包含 bundle 对象,
809
+ // 可以通过调用 bundle.generate
810
+ // 或 bundle.write 来生成其他输出。
811
+ // 当使用 watch.skipWrite 选项时,这尤其重要。
812
+ // 生成输出后,你应该调用 "event.result.close()",
813
+ // 或者如果你不生成输出,也应该调用。
814
+ // 这将允许插件通过
815
+ // "closeBundle" 钩子清理资源。
816
+ // END - 完成所有产物的构建
817
+ // ERROR - 在打包时遇到错误
818
+ // * event.error 包含抛出的错误
819
+ // * 对于构建错误,event.result 为 null,
820
+ // 对于输出生成错误,它包含 bundle 对象。
821
+ // 与 "BUNDLE_END" 一样,如果存在,
822
+ // 你应该在完成后调用 "event.result.close()"。
823
+ // 如果从事件处理程序返回一个 Promise,则 Rollup
824
+ // 将等待 Promise 解析后再继续。
825
+
826
+ watcher.on('event', function (event) {
827
+ var _event$result;
828
+ switch (event.code) {
829
+ case 'BUNDLE_END':
830
+ // 这将确保在每次运行后正确关闭打包
831
+ cLog.info('serve', event.code, "\u5355\u6B21\u6253\u5305\u5B8C\u6210");
832
+ event.result.close();
833
+ break;
834
+ case 'ERROR':
835
+ cLog.error('serve', event.code, "\u5355\u6B21\u6253\u5305\u6355\u83B7\u5230\u9519\u8BEF");
836
+ handleError(event.error, true);
837
+ (_event$result = event.result) === null || _event$result === void 0 || _event$result.close();
838
+ break;
839
+ case 'BUNDLE_START':
840
+ cLog.log('serve', event.code, "\u5355\u6B21\u6253\u5305\u4E2D....");
841
+ break;
842
+ case 'END':
843
+ cLog.info('serve', event.code, "\u5B8C\u6210\u5355\u6B21\u6784\u5EFA");
844
+ break;
845
+ case 'START':
846
+ cLog.log('serve', event.code, "\u76D1\u89C6\u5668\u6B63\u5728\uFF08\u91CD\u65B0\uFF09\u542F\u52A8");
847
+ break;
848
+ }
849
+ });
850
+
851
+ // 此外,你可以挂钩以下内容。
852
+ // 同样,返回 Promise 以使 Rollup 在该阶段等待:
853
+ watcher.on('change', function (id, _ref) {
854
+ var event = _ref.event;
855
+ /* 更改了一个文件 */
856
+ cLog.log('serve', event.toUpperCase(), "".concat('检测到文件变动'.padEnd(12, ' '), " \u27A9 ").concat(picocolors.cyan(relative(getCwd(), id))));
857
+ });
858
+ watcher.on('restart', function () {
859
+ /* 新触发了一次运行 */
860
+ cLog.log('serve', 'restart'.toUpperCase(), '新触发了一次运行');
861
+ });
862
+ watcher.on('close', function () {
863
+ /* 监视器被关闭了,请看下面的代码 */
864
+ });
865
+ };
866
+ var _picocolors$createCol = picocolors.createColors(),
867
+ bold = _picocolors$createCol.bold,
868
+ cyan = _picocolors$createCol.cyan,
869
+ dim = _picocolors$createCol.dim,
870
+ red = _picocolors$createCol.red;
871
+
872
+ // log to stderr to keep `rollup main.js > bundle.js` from breaking
873
+ var stderr = function stderr() {
874
+ for (var _len = arguments.length, parameters = new Array(_len), _key = 0; _key < _len; _key++) {
875
+ parameters[_key] = arguments[_key];
876
+ }
877
+ return process.stderr.write("".concat(parameters.join(''), "\n"));
878
+ };
879
+ function handleError(error) {
880
+ var _error$cause;
881
+ var recover = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
882
+ var name = error.name || ((_error$cause = error.cause) === null || _error$cause === void 0 ? void 0 : _error$cause.name);
883
+ var nameSection = name ? "".concat(name, ": ") : '';
884
+ var pluginSection = error.plugin ? "(plugin ".concat(error.plugin, ") ") : '';
885
+ var message = "".concat(pluginSection).concat(nameSection).concat(error.message);
886
+ var outputLines = [bold(red("[!] ".concat(bold(message.toString()))))];
887
+ if (error.url) {
888
+ outputLines.push(cyan(error.url));
889
+ }
890
+ if (error.loc) {
891
+ outputLines.push(" (".concat(error.loc.line, ":").concat(error.loc.column, ")"));
892
+ }
893
+ if (error.frame) {
894
+ outputLines.push(dim(error.frame));
895
+ }
896
+ if (error.stack) {
897
+ var _error$stack;
898
+ outputLines.push(dim((_error$stack = error.stack) === null || _error$stack === void 0 ? void 0 : _error$stack.replace("".concat(nameSection).concat(error.message, "\n"), '')));
899
+ }
900
+ outputLines.push('', '');
901
+ stderr(outputLines.join('\n'));
902
+ if (!recover) process.exit(1);
903
+ }
904
+
905
+ var rollupWatch = function rollupWatch(config) {
906
+ return watch(config);
907
+ };
908
+
909
+ export { Ctx, createRollupBuild, dealDts, getAliasPlugin, getBabelPlugin, getCommonjsPlugin, getCopyPlugin, getDtsPlugin, getExternal, getFirstInput, getInput, getJsonPlugin, getMinimizePlugin, getNodePlugins, getOutput, getPostcssPlugin, getReactPlugins, getResolvePlugin, getRollupWrite, getWatch, handleError, rollupWatch, rollupWatchLog };