@tmsfe/tmskit 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.
Files changed (39) hide show
  1. package/CHANGELOG.md +0 -0
  2. package/README.md +24 -0
  3. package/dist/index.cjs.js +2248 -0
  4. package/main.js +3 -0
  5. package/package.json +72 -0
  6. package/rollup.config.js +179 -0
  7. package/src/config/constant.js +65 -0
  8. package/src/config/defaultTmsConfig.js +17 -0
  9. package/src/entry.js +20 -0
  10. package/src/index.js +47 -0
  11. package/src/init.js +38 -0
  12. package/src/scripts/create/ask.js +61 -0
  13. package/src/scripts/create/generator.js +27 -0
  14. package/src/scripts/create/ignoreFiles.js +7 -0
  15. package/src/scripts/create/index.js +65 -0
  16. package/src/scripts/create/render.js +19 -0
  17. package/src/scripts/run/build/index.js +16 -0
  18. package/src/scripts/run/dev/index.js +67 -0
  19. package/src/scripts/run/index.js +57 -0
  20. package/src/scripts/run/init/index.js +97 -0
  21. package/src/utils/buildAppJson.js +144 -0
  22. package/src/utils/checkDependencies.js +77 -0
  23. package/src/utils/cliUtils.js +35 -0
  24. package/src/utils/cloneModules.js +90 -0
  25. package/src/utils/global.js +36 -0
  26. package/src/utils/io.js +21 -0
  27. package/src/utils/log.js +44 -0
  28. package/src/utils/mpCiUtils.js +74 -0
  29. package/src/utils/npmUtils.js +126 -0
  30. package/src/utils/tkitUtils.js +84 -0
  31. package/src/utils/widgets.js +177 -0
  32. package/src/webpack/base.js +65 -0
  33. package/src/webpack/build.js +21 -0
  34. package/src/webpack/buildServer.js +34 -0
  35. package/src/webpack/dev.js +31 -0
  36. package/src/webpack/devServer.js +37 -0
  37. package/src/webpack/plugins/entryExtractPlugin/index.js +29 -0
  38. package/src/webpack/plugins/px2rpx/index.js +14 -0
  39. package/src/webpack/utils.js +244 -0
@@ -0,0 +1,2248 @@
1
+ 'use strict';
2
+
3
+ var require$$0 = require('commander');
4
+ var require$$1 = require('leven');
5
+ var require$$2 = require('ora');
6
+ var require$$1$1 = require('path');
7
+ var require$$1$2 = require('fs');
8
+ var require$$5 = require('shelljs');
9
+ var require$$6$1 = require('download-git-repo');
10
+ var require$$0$1 = require('chalk');
11
+ var require$$0$2 = require('async');
12
+ var require$$1$3 = require('ejs');
13
+ var require$$1$4 = require('inquirer');
14
+ var require$$0$3 = require('metalsmith');
15
+ var require$$0$4 = require('miniprogram-ci');
16
+ var require$$0$5 = require('lodash');
17
+ var require$$7 = require('replace-ext');
18
+ var require$$0$6 = require('webpack-chain');
19
+ var require$$0$7 = require('webpack');
20
+ var require$$0$8 = require('webpack/lib/SingleEntryPlugin');
21
+ var require$$3$1 = require('copy-webpack-plugin');
22
+ var require$$1$5 = require('semver');
23
+
24
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
25
+
26
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
27
+ var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
28
+ var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2);
29
+ var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
30
+ var require$$1__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$1$2);
31
+ var require$$5__default = /*#__PURE__*/_interopDefaultLegacy(require$$5);
32
+ var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6$1);
33
+ var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
34
+ var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
35
+ var require$$1__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$1$3);
36
+ var require$$1__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$1$4);
37
+ var require$$0__default$3 = /*#__PURE__*/_interopDefaultLegacy(require$$0$3);
38
+ var require$$0__default$4 = /*#__PURE__*/_interopDefaultLegacy(require$$0$4);
39
+ var require$$0__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$0$5);
40
+ var require$$7__default = /*#__PURE__*/_interopDefaultLegacy(require$$7);
41
+ var require$$0__default$6 = /*#__PURE__*/_interopDefaultLegacy(require$$0$6);
42
+ var require$$0__default$7 = /*#__PURE__*/_interopDefaultLegacy(require$$0$7);
43
+ var require$$0__default$8 = /*#__PURE__*/_interopDefaultLegacy(require$$0$8);
44
+ var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3$1);
45
+ var require$$1__default$5 = /*#__PURE__*/_interopDefaultLegacy(require$$1$5);
46
+
47
+ function getAugmentedNamespace(n) {
48
+ if (n.__esModule) return n;
49
+ var a = Object.defineProperty({}, '__esModule', {value: true});
50
+ Object.keys(n).forEach(function (k) {
51
+ var d = Object.getOwnPropertyDescriptor(n, k);
52
+ Object.defineProperty(a, k, d.get ? d : {
53
+ enumerable: true,
54
+ get: function () {
55
+ return n[k];
56
+ }
57
+ });
58
+ });
59
+ return a;
60
+ }
61
+
62
+ var src$1 = {};
63
+
64
+ const program$1 = require$$0__default;
65
+ const leven = require$$1__default;
66
+ const ora = require$$2__default;
67
+ const path$6 = require$$1__default$1;
68
+ const fs$c = require$$1__default$2;
69
+ const shelljs$5 = require$$5__default;
70
+ const download = require$$6__default;
71
+ const chalk$3 = require$$0__default$1;
72
+ const shelljsOptons = {
73
+ slient: true
74
+ }; // 获取当前目录
75
+
76
+ const cwd = process.cwd();
77
+
78
+ function resolve$a(...args) {
79
+ return path$6.resolve(cwd, ...args);
80
+ }
81
+ /**
82
+ * 封装logs
83
+ * @returns {Undefined} 无需返回值
84
+ */
85
+
86
+ const log$3 = (...args) => console.log(...args);
87
+ /**
88
+ * 用户输入命令时,进行提示
89
+ * @param {String} unknownCommand 非预期的命令
90
+ * @returns {Undefined} 无需返回值
91
+ */
92
+
93
+
94
+ const suggestCommands$1 = unknownCommand => {
95
+ const availableCommands = program$1.commands.map(cmd => cmd._name);
96
+ let suggestion;
97
+ availableCommands.forEach(cmd => {
98
+ const isBestMatch = leven(cmd, unknownCommand) < leven(suggestion || '', unknownCommand);
99
+
100
+ if (leven(cmd, unknownCommand) < 3 && isBestMatch) {
101
+ suggestion = cmd;
102
+ }
103
+ });
104
+
105
+ if (suggestion) {
106
+ log$3(` ${chalk$3.red(`Did you mean ${chalk$3.yellow(suggestion)}?`)}`);
107
+ }
108
+ };
109
+ /**
110
+ * 判断变量是否是一个数组
111
+ * @param { unknown } obj 变量
112
+ * @returns { boolean } 是否是一个数组
113
+ */
114
+
115
+
116
+ function isObject$2(obj) {
117
+ return Object.prototype.toString.call(obj) === '[object Object]';
118
+ }
119
+ /**
120
+ * 判断变量是否是一个对象
121
+ * @param { unknown } obj 变量
122
+ * @returns { boolean } 是否是一个对象
123
+ */
124
+
125
+
126
+ function isArray$1(obj) {
127
+ return Object.prototype.toString.call(obj) === '[object Array]';
128
+ }
129
+ /**
130
+ * 下载模块到目标目录
131
+ * @param { string } dest 目标地址
132
+ * @param { object } downloadOptions 模块下载配置 { repoUrl-仓库地址, gitUrl-git地址, branch-分支或者tag }
133
+ * @returns { undefined } no return
134
+ */
135
+
136
+
137
+ function downloadRepo(dest, downloadOptions = {
138
+ repoUrl: '',
139
+ gitUrl: '',
140
+ branch: ''
141
+ }) {
142
+ const {
143
+ repoUrl,
144
+ gitUrl,
145
+ branch
146
+ } = downloadOptions;
147
+
148
+ if (fs$c.existsSync(dest)) {
149
+ shelljs$5.rm('-rf', dest);
150
+ }
151
+
152
+ shelljs$5.mkdir('-p', dest);
153
+ return new Promise(resolve => {
154
+ download(`${repoUrl}#${branch}`, dest, {
155
+ clone: true
156
+ }, async e => {
157
+ if (e) {
158
+ console.log(e); // eslint-disable-line
159
+
160
+ await downloadRepoForGit$2(gitUrl, dest, branch);
161
+ }
162
+
163
+ resolve();
164
+ });
165
+ });
166
+ }
167
+ /**
168
+ * 下载模块到目标目录备用方案
169
+ * @param { string } url 模块地址
170
+ * @param { string } dest 目标地址
171
+ * @param { string } branch 分支名
172
+ * @returns { undefined } no return
173
+ */
174
+
175
+
176
+ function downloadRepoForGit$2(url, dest, branch) {
177
+ const cwd = process.cwd();
178
+ return new Promise((resolve, reject) => {
179
+ // 如果目标目录不存在
180
+ if (fs$c.existsSync(dest)) {
181
+ shelljs$5.rm('-rf', path$6.join(dest));
182
+ }
183
+
184
+ shelljs$5.mkdir('-p', dest);
185
+ shelljs$5.cd(dest);
186
+ shelljs$5.exec(`git clone ${url} ${dest} --depth=1`, shelljsOptons);
187
+ shelljs$5.exec(`git checkout ${branch}`, code => {
188
+ if (code === 0) {
189
+ shelljs$5.cd(cwd);
190
+ resolve();
191
+ }
192
+
193
+ reject();
194
+ });
195
+ });
196
+ }
197
+ /**
198
+ * 计算各项任务耗时
199
+ * @param {Number} start 任务开始时间
200
+ * @returns {Undefined} 无需返回值
201
+ */
202
+
203
+
204
+ const cost = start => Date.now() - start;
205
+ /**
206
+ * 创建构建子任务
207
+ * @param {Function} task 子任务执行函数
208
+ * @param {String} startText 任务开始前提示语
209
+ * @param {String} endText 任务结束后提示语
210
+ * @returns {Undefined} 无需返回值
211
+ */
212
+
213
+
214
+ function createTask$4(task, startText, endText) {
215
+ return async (...args) => {
216
+ const start = Date.now();
217
+ let result;
218
+ const spinner = ora(startText);
219
+ spinner.start();
220
+
221
+ try {
222
+ result = await task(...args);
223
+ } catch (e) {
224
+ result = e;
225
+ console.log(chalk$3.red(e));
226
+ process.exit(-1);
227
+ } finally {
228
+ endText && spinner.succeed(`${endText}, ${cost(start)}ms`);
229
+ spinner.stop();
230
+ }
231
+
232
+ return result;
233
+ };
234
+ }
235
+ /**
236
+ * 字符串驼峰化处理
237
+ * @param {String} str 需要处理的字符串
238
+ * @returns {String} 经过驼峰处理的字符串
239
+ */
240
+
241
+ const camelize = str => str.replace(/-(\w)/g, (a, c) => c ? c.toUpperCase() : '');
242
+
243
+ var widgets = {
244
+ resolve: resolve$a,
245
+ log: log$3,
246
+ isObject: isObject$2,
247
+ isArray: isArray$1,
248
+ createTask: createTask$4,
249
+ downloadRepo,
250
+ downloadRepoForGit: downloadRepoForGit$2,
251
+ suggestCommands: suggestCommands$1,
252
+ camelize
253
+ };
254
+
255
+ const path$5 = require('path'); // 用户目录
256
+
257
+
258
+ const HOME_DIR = process.env.HOME; // 所有文件的缓存目录
259
+
260
+ const CACHE_DIR$1 = path$5.resolve(HOME_DIR, '.tmskit'); // 脚手架模板代码所在目录
261
+
262
+ const TEMPLATE_DIR$1 = path$5.resolve(CACHE_DIR$1, 'template'); // 第三方模块源码存放的临时缓存目录
263
+
264
+ const MODULE_CODE_DIR$1 = path$5.resolve(CACHE_DIR$1, 'modules_code'); // 脚手架模板代码的具体路径
265
+
266
+ const TEMPLATE_PATH$1 = path$5.resolve(TEMPLATE_DIR$1, 'tools/tms-cli-template'); // 脚手架的名称
267
+
268
+ const TMS_NAME$2 = 'tmskit'; // 脚手架的配置名称
269
+
270
+ const TMS_CONFIG_FILENAME$1 = 'tms.config.js'; // 模块代码的默认在modules子目录
271
+
272
+ const DEFAULT_MODULE_DIR$5 = 'modules'; // 模块的配置文件的名称
273
+
274
+ const MODULE_CONFIG_FILENAME$2 = 'module.config.json'; // 默认的webpack entry
275
+
276
+ const DEFAULT_WEBPACK_ENTRY$2 = {
277
+ app: path$5.resolve(process.cwd(), 'app')
278
+ }; // 默认从源码拷贝到编译后的配置
279
+
280
+ const DEFAULT_COPY_CONFIG$3 = ['package.json', 'app.js', 'app.ts', 'app.less', 'app.wxss', 'sitemap.json']; // 开发模式
281
+
282
+ const MODE$1 = {
283
+ main: 'tkitmain',
284
+ all: 'all',
285
+ multi: 'multi'
286
+ };
287
+ const ENV = {
288
+ dev: 'development',
289
+ prod: 'production'
290
+ };
291
+
292
+ var constant = /*#__PURE__*/Object.freeze({
293
+ __proto__: null,
294
+ HOME_DIR: HOME_DIR,
295
+ CACHE_DIR: CACHE_DIR$1,
296
+ TEMPLATE_DIR: TEMPLATE_DIR$1,
297
+ TEMPLATE_PATH: TEMPLATE_PATH$1,
298
+ TMS_NAME: TMS_NAME$2,
299
+ TMS_CONFIG_FILENAME: TMS_CONFIG_FILENAME$1,
300
+ DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR$5,
301
+ MODULE_CONFIG_FILENAME: MODULE_CONFIG_FILENAME$2,
302
+ DEFAULT_WEBPACK_ENTRY: DEFAULT_WEBPACK_ENTRY$2,
303
+ DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$3,
304
+ MODULE_CODE_DIR: MODULE_CODE_DIR$1,
305
+ MODE: MODE$1,
306
+ ENV: ENV
307
+ });
308
+
309
+ var require$$3 = /*@__PURE__*/getAugmentedNamespace(constant);
310
+
311
+ const fs$b = require$$1__default$2;
312
+ /**
313
+ * 判断目录是否为空
314
+ * @param {string} dirname 目录名
315
+ * @returns
316
+ */
317
+
318
+ const isDirEmpty = dirname => fs$b.promises.readdir(dirname).then(files => files.length === 0);
319
+ /**
320
+ * 确保目录存在,不存在就创建一个
321
+ * @param {*} dirname 目录名
322
+ */
323
+
324
+
325
+ const ensureDirExist = dirname => {
326
+ if (!fs$b.existsSync(dirname)) {
327
+ fs$b.mkdirSync(dirname, {
328
+ recursive: true
329
+ });
330
+ }
331
+ };
332
+
333
+ var io$2 = {
334
+ isDirEmpty,
335
+ ensureDirExist
336
+ };
337
+
338
+ const chalk$2 = require$$0__default$1;
339
+ /**
340
+ * 本文件提供无依赖的在终端打印彩色文字的方法。
341
+ */
342
+
343
+ const resetCfg = decodeURIComponent('%1B%5B0m'); // \033[0m转义后的字符按,用来还原属性
344
+
345
+ /**
346
+ * 打印红底黑字格式的文字
347
+ * @param {String} message 需要打印的文字信息
348
+ * @returns {undefined} 无
349
+ */
350
+
351
+ const fail$a = (message = '') => {
352
+ const redStyleConfig = decodeURIComponent('%1B%5B41%3B30m'); // \033[41;30m转义后的字符按,console时输出红色文字
353
+
354
+ const greenFontStyleConfig = decodeURIComponent('%1B%5B41%3B37m'); // \033[41;30m转义后的字符按,console时输出红底白色文字
355
+
356
+ console.log(`${redStyleConfig} ERROR ${greenFontStyleConfig} ${message}${resetCfg}`); // eslint-disable-line no-console
357
+ };
358
+ /**
359
+ * 打印绿底黑字格式的文字
360
+ * @param {String} message 需要打印的文字信息
361
+ * @returns {undefined} 无
362
+ */
363
+
364
+
365
+ const succeed$1 = (message = '') => {
366
+ const greenStyleConfig = decodeURIComponent('%1B%5B42%3B30m'); // \033[42;30m转义后的字符按,console时输出绿色文字
367
+
368
+ const greenFontStyleConfig = decodeURIComponent('%1B%5B40%3B32m'); // \033[40;32m转义后的字符按,console时输出绿色文字
369
+
370
+ console.log(`${greenStyleConfig} Success ${greenFontStyleConfig} ${message}${resetCfg}`); // eslint-disable-line no-console
371
+ };
372
+ /**
373
+ * 打印warn提示
374
+ * @param {String} message 需要打印的文字信息
375
+ * @returns {undefined} 无
376
+ */
377
+
378
+
379
+ const warn = message => {
380
+ console.log(chalk$2.yellow(message));
381
+ };
382
+
383
+ var log$2 = {
384
+ fail: fail$a,
385
+ succeed: succeed$1,
386
+ warn
387
+ };
388
+
389
+ const async = require$$0__default$2;
390
+ const ejs = require$$1__default$3;
391
+
392
+ const render$1 = (files, metalsmith, next) => {
393
+ const keys = Object.keys(files);
394
+ const metadata = metalsmith.metadata();
395
+
396
+ const run = (file, next) => {
397
+ const str = files[file].contents.toString();
398
+ const newStr = ejs.render(str, metadata); // eslint-disable-next-line
399
+
400
+ files[file].contents = Buffer.from(newStr);
401
+ next();
402
+ };
403
+
404
+ async.each(keys, run, next);
405
+ };
406
+
407
+ var render_1 = render$1;
408
+
409
+ const fs$a = require$$1__default$2;
410
+ const inquirer = require$$1__default$4;
411
+ /**
412
+ * 获取模板内的问题
413
+ * @param {string} templateDir 模板目录
414
+ * @returns {Array} inquirer 问题数组
415
+ */
416
+
417
+ const parseTemplateQuestions = templateDir => {
418
+ let prompts = [];
419
+
420
+ if (!fs$a.existsSync(`${templateDir}/questions.json`)) {
421
+ return prompts;
422
+ }
423
+
424
+ try {
425
+ const json = JSON.parse(fs$a.readFileSync(`${templateDir}/questions.json`));
426
+
427
+ if (Array.isArray(json) && json.length > 0) {
428
+ json.forEach((item, index) => {
429
+ if (!isQuestionType(item)) {
430
+ throw new Error(`第 ${index} 个问题不符合"inquirer"的格式要求`);
431
+ }
432
+ });
433
+ } else {
434
+ throw new Error('问题文件只能是数组');
435
+ }
436
+
437
+ prompts = json;
438
+ } catch (err) {
439
+ throw new Error(`模板异常,${err.message}`);
440
+ }
441
+
442
+ return prompts;
443
+ };
444
+
445
+ const isQuestionType = result => {
446
+ if (!('message' in result)) {
447
+ return false;
448
+ }
449
+
450
+ if (!('name' in result)) {
451
+ return false;
452
+ }
453
+
454
+ return true;
455
+ };
456
+
457
+ const ask$1 = templateDir => (files, metalsmith, next) => {
458
+ const prompts = parseTemplateQuestions(templateDir);
459
+ const metadata = metalsmith.metadata();
460
+ const filteredPrompts = prompts.filter(prompt => {
461
+ if (metadata[prompt.name] && `${metadata[prompt.name]}`.trim() !== '') {
462
+ return false;
463
+ }
464
+
465
+ return true;
466
+ });
467
+ inquirer.prompt(filteredPrompts).then(res => {
468
+ for (const prompt of filteredPrompts) {
469
+ metadata[prompt.name] = res[prompt.name];
470
+ }
471
+
472
+ next();
473
+ }).catch(err => {
474
+ next(err);
475
+ });
476
+ };
477
+
478
+ var ask_1 = ask$1;
479
+
480
+ const FILES_TO_IGNORE$1 = ['node_modules'];
481
+ var ignoreFiles = FILES_TO_IGNORE$1;
482
+
483
+ const Metalsmith = require$$0__default$3;
484
+ const fs$9 = require$$1__default$2;
485
+ const render = render_1;
486
+ const ask = ask_1;
487
+ const FILES_TO_IGNORE = ignoreFiles;
488
+
489
+ const generator$1 = (buildDir, distDir, preMetadata) => new Promise((resolve, reject) => {
490
+ Metalsmith(buildDir).metadata(preMetadata).ignore(FILES_TO_IGNORE).clean(false).use(ask(buildDir)).source('./').destination(distDir).use(render).build(err => {
491
+ if (err) {
492
+ reject(err);
493
+ } else {
494
+ fs$9.unlinkSync(`${distDir}/questions.json`);
495
+ resolve('finish');
496
+ }
497
+ });
498
+ });
499
+
500
+ var generator_1 = generator$1;
501
+
502
+ const path$4 = require$$1__default$1;
503
+ const fs$8 = require$$1__default$2;
504
+ const shelljs$4 = require$$5__default;
505
+ const {
506
+ TEMPLATE_DIR,
507
+ TEMPLATE_PATH
508
+ } = require$$3;
509
+ const {
510
+ downloadRepoForGit: downloadRepoForGit$1,
511
+ createTask: createTask$3,
512
+ resolve: resolve$9
513
+ } = widgets;
514
+ const io$1 = io$2;
515
+ const {
516
+ fail: fail$9,
517
+ succeed
518
+ } = log$2;
519
+ const generator = generator_1;
520
+ /**
521
+ * 如果该目录下面存在文件,换个名字
522
+ * @param { string } targetDir 当前文件夹
523
+ * @returns { undefined }
524
+ */
525
+
526
+ async function createAppDir(targetDir) {
527
+ // 如果目录非空或者已经存在,提示用户,做选择
528
+ if (fs$8.existsSync(targetDir)) {
529
+ if (!(await io$1.isDirEmpty(targetDir))) {
530
+ fail$9('该目录名已经存在,换个项目名字吧~');
531
+ process.exit(1);
532
+ }
533
+ } else {
534
+ shelljs$4.mkdir('-p', targetDir);
535
+ }
536
+ }
537
+ /**
538
+ * 创建本地小程序运行环境
539
+ * @param { string } appType 项目类型
540
+ * @param { string } appName 项目名称
541
+ */
542
+
543
+
544
+ async function create(appName) {
545
+ const cwd = process.cwd();
546
+ const targetDir = path$4.resolve(cwd, appName);
547
+ const appType = 'mp';
548
+ createAppDir(targetDir); // 创建缓存目录
549
+
550
+ io$1.ensureDirExist(TEMPLATE_DIR); // 拉取git模板
551
+
552
+ await createTask$3(downloadRepoForGit$1, '拉取模板仓库', '拉取模板仓库完成')('https://git.woa.com/tmsfe/tms-frontend.git', TEMPLATE_DIR, 'master'); // 生成模板(1. 询问问题, 2. ejs生成模板 3.生成到目标目录)
553
+
554
+ generator(path$4.join(TEMPLATE_PATH, appType), targetDir, {
555
+ appName,
556
+ appType
557
+ }).then(() => {
558
+ succeed('项目创建完成,开始初始化...');
559
+ shelljs$4.cd(appName); // 初始化构件主包的代码, 让用户打开项目可以跑起来
560
+
561
+ if (fs$8.existsSync(resolve$9(`${appName}/tms.config.js`))) {
562
+ shelljs$4.exec('tmskit run build');
563
+ }
564
+ }).catch(err => {
565
+ fail$9(err.message);
566
+ console.log('详细的错误信息:', err);
567
+ });
568
+ }
569
+
570
+ var create_1 = create;
571
+
572
+ const fs$7 = require$$1__default$2;
573
+ const {
574
+ DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR$4,
575
+ MODULE_CONFIG_FILENAME: MODULE_CONFIG_FILENAME$1
576
+ } = require$$3;
577
+ const {
578
+ fail: fail$8
579
+ } = log$2;
580
+ const {
581
+ resolve: resolve$8,
582
+ isObject: isObject$1,
583
+ isArray
584
+ } = widgets;
585
+ /**
586
+ * 获取每个模块下面的信息,并且收集,后续更新到appJson里面
587
+ * @param { object } file 操作目录下面所有的文件
588
+ * @param { string } appName 小程序的名称
589
+ */
590
+
591
+ function setModuleConfig$1(file, appName, moduleDir) {
592
+ const content = file.contents ? JSON.parse(file.contents.toString()) : JSON.parse(file);
593
+
594
+ if (isObject$1(content)) {
595
+ content.root = content.root.indexOf(moduleDir) > -1 ? content.root : `${moduleDir}/${content.root}`;
596
+ }
597
+
598
+ if (isArray(content)) {
599
+ let i = content.length - 1;
600
+
601
+ while (i >= 0) {
602
+ let current = content[i];
603
+ current.root = current.root.indexOf(moduleDir) > -1 ? current.root : `${moduleDir}/${current.root}`;
604
+
605
+ if (appName && current.mpConfig && current.mpConfig[appName]) {
606
+ current = { ...current,
607
+ ...current.mpConfig[appName]
608
+ };
609
+ }
610
+
611
+ delete current.mpConfig;
612
+ delete current.isSubpackages;
613
+ content[i] = current;
614
+ i--; // eslint-disable-line
615
+ }
616
+ }
617
+
618
+ return content;
619
+ }
620
+ /**
621
+ * 递归获取本地所有模块的配置信息
622
+ */
623
+
624
+
625
+ function getLocalModuleConfig(modules = [], appName, moduleDir, moduleConfigFilename) {
626
+ const modulesConfig = {};
627
+ modules.forEach(({
628
+ path
629
+ }) => {
630
+ const moduleConfigPath = resolve$8(path, moduleConfigFilename);
631
+
632
+ if (fs$7.existsSync(moduleConfigPath)) {
633
+ const content = fs$7.readFileSync(moduleConfigPath, 'utf-8');
634
+ modulesConfig[moduleConfigPath] = setModuleConfig$1(content, appName, moduleDir);
635
+ }
636
+ });
637
+ return modulesConfig;
638
+ }
639
+ /**
640
+ * 更新appJson里面的首页配置
641
+ * @param { object } appJson appJson信息
642
+ * @param { array } mainPackages 小程序主包信息
643
+ * @returns { object } appJson小程序主页配置信息
644
+ */
645
+
646
+
647
+ function updateMainPackages(appJson, mainPackages = []) {
648
+ let foundMainPackages = appJson.subpackages.filter(subpackage => mainPackages.includes(subpackage.name));
649
+
650
+ if (foundMainPackages.length === 0) {
651
+ // 没找到主包
652
+ foundMainPackages = [appJson.subpackages[0]];
653
+ } // 拼装 app.pages
654
+
655
+
656
+ foundMainPackages.forEach(subpackage => {
657
+ if (!subpackage.pages || !subpackage.pages.length) {
658
+ fail$8(`主包 ${subpackage} 不能没有 pages`);
659
+ process.exit(-1);
660
+ }
661
+
662
+ subpackage.pages.forEach(page => {
663
+ appJson.pages.push(`${subpackage.root}/${page}`);
664
+ });
665
+
666
+ if (subpackage.plugins) {
667
+ Object.assign(appJson.plugins, subpackage.plugins);
668
+ }
669
+ }); // 去掉 subpackages 中的主包配置
670
+
671
+ const foundMainPackageNames = foundMainPackages.map(item => item.name); // eslint-disable-next-line
672
+
673
+ appJson.subpackages = appJson.subpackages.filter(subpackage => !foundMainPackageNames.includes(subpackage.name));
674
+ return appJson;
675
+ }
676
+ /**
677
+ * 获取app.json内容
678
+ * @param {string} sourceAppJsonPath
679
+ * @returns
680
+ */
681
+
682
+
683
+ const getAppJsonContent = sourceAppJsonPath => {
684
+ if (!fs$7.existsSync(sourceAppJsonPath)) {
685
+ fail$8(`当前路径 ${sourceAppJsonPath} 没找到app.json`);
686
+ process.exit(1);
687
+ }
688
+
689
+ const appJson = JSON.parse(fs$7.readFileSync(sourceAppJsonPath), 'utf-8'); // 加入默认值
690
+
691
+ appJson.subpackages = [];
692
+ appJson.pages = [];
693
+ appJson.plugins = {};
694
+ delete appJson.entranceDeclare;
695
+ return appJson;
696
+ };
697
+ /**
698
+ * 更新app.json中的subpackages
699
+ * @param {Object} appJson
700
+ * @param {Object} modulesConfig
701
+ */
702
+
703
+
704
+ const updateSubpackages = (appJson, modulesConfig) => {
705
+ // eslint-disable-next-line
706
+ for (const name in modulesConfig) {
707
+ const moduleInfo = isObject$1(modulesConfig[name]) ? [modulesConfig[name]] : modulesConfig[name]; // eslint-disable-next-line
708
+
709
+ appJson.subpackages = appJson.subpackages.concat(moduleInfo);
710
+ }
711
+ };
712
+ /**
713
+ * 动态生成编译后的app.json
714
+ * @param {object} tmsConfig
715
+ * @param {array} modules
716
+ * @returns
717
+ */
718
+
719
+
720
+ function buildOutputAppJson$2(tmsConfig, modules) {
721
+ // 获取当前 modules 下的所有子模块的配置内容
722
+ const modulesConfig = getLocalModuleConfig(modules, tmsConfig.appName, DEFAULT_MODULE_DIR$4, MODULE_CONFIG_FILENAME$1); // 获取app.json的配置
723
+
724
+ const appJson = getAppJsonContent(resolve$8('./app.json')); // 更新app.json中的subpackages
725
+
726
+ updateSubpackages(appJson, modulesConfig); // 更新主包,需在subpackages处理完成后执行, pages/
727
+
728
+ updateMainPackages(appJson, tmsConfig.mainPackages);
729
+ fs$7.writeFileSync(resolve$8(`${tmsConfig.webpack.outputDir}/app.json`), JSON.stringify(appJson, null, 2), 'utf8');
730
+ return appJson;
731
+ }
732
+
733
+ var buildAppJson = {
734
+ setModuleConfig: setModuleConfig$1,
735
+ buildOutputAppJson: buildOutputAppJson$2
736
+ };
737
+
738
+ /**
739
+ * 本文件主要负责项目或者分包依赖的npm的安装
740
+ */
741
+ const fs$6 = require$$1__default$2;
742
+ const path$3 = require$$1__default$1;
743
+ const shell = require$$5__default;
744
+ const LOG = log$2;
745
+ const dirpath = process.cwd(); // 项目根目录
746
+
747
+ const getTarNpmFilename = targetDir => `${targetDir.replaceAll('/', '-')}.tar.gz`; // 缓存npm包
748
+
749
+
750
+ const npmCache = function (targetDir, cacheDir) {
751
+ if (!fs$6.existsSync(cacheDir)) {
752
+ fs$6.mkdirSync(cacheDir);
753
+ }
754
+
755
+ const tarNpmFilename = getTarNpmFilename(targetDir);
756
+ const tarNpmFilePath = `${cacheDir}/${tarNpmFilename}`;
757
+
758
+ if (fs$6.existsSync(tarNpmFilePath)) {
759
+ shell.rm('-rf', tarNpmFilePath);
760
+ }
761
+
762
+ const cmd = `tar -zcvf ${tarNpmFilePath} ./node_modules`;
763
+ shell.exec(cmd, {
764
+ async: true,
765
+ silent: true
766
+ }); // tar -zcvf /Users/odile/.tmskit/node_modules.tar.gz ./node_modules
767
+ }; // 获取缓存npm包
768
+
769
+
770
+ const getNpmCache = function (targetDir, cacheDir) {
771
+ const tarNpmFilename = getTarNpmFilename(targetDir);
772
+ const tarNpmFilePath = `${cacheDir}/${tarNpmFilename}`;
773
+
774
+ if (fs$6.existsSync(tarNpmFilePath)) {
775
+ const cmd = `tar -zxvf ${tarNpmFilePath} -C ./`;
776
+ shell.exec(cmd, {
777
+ async: false,
778
+ silent: true
779
+ });
780
+ } // tar -zxvf /Users/odile/.tmskit/node_modules.tar.gz -C ./
781
+
782
+ }; // 遍历安装指定目录下所有项目的npm依赖
783
+
784
+
785
+ const npmInstallAll$1 = async (modules, contextDir, cacheDir) => {
786
+ const packageJsonFiles = await findAllPackageJson$1(modules, contextDir);
787
+ await Promise.all(packageJsonFiles.map(file => new Promise(resolve => {
788
+ const dir = path$3.dirname(file);
789
+ shell.cd(dir);
790
+
791
+ if (!fs$6.existsSync(`${dir}/node_modules`)) {
792
+ getNpmCache(dir, cacheDir);
793
+ }
794
+
795
+ shell.exec('npx pnpm install --prod --registry http://mirrors.tencent.com/npm/', {
796
+ silent: false
797
+ });
798
+ resolve();
799
+ npmCache(dir, cacheDir);
800
+ })));
801
+ };
802
+ /**
803
+ * 递归查找指定条件的文件
804
+ * @param {String} startPath 开始查找的根路径
805
+ * @param {String} filter 匹配的字符串
806
+ * @returns {Array<String>} 查找到的文件路径列表
807
+ */
808
+
809
+
810
+ const findFilesByFilter = (startPath, filter) => {
811
+ const result = [];
812
+ /**
813
+ * 根据指定的筛选器查找文件
814
+ * @param {String} startPath 开始查找的文件夹路径
815
+ * @param {String} filter 筛选器
816
+ * @returns {Undefined} 无需返回值
817
+ */
818
+
819
+ const find = (startPath, filter) => {
820
+ // 目录不存在
821
+ if (!fs$6.existsSync(startPath)) {
822
+ LOG.fail(`${startPath}目录不存在`);
823
+ process.exit(-1);
824
+ return;
825
+ } // 当前目录下的所有文件 / 文件夹
826
+
827
+
828
+ const exceptDir = ['node_modules', 'miniprogram_npm'];
829
+
830
+ if (exceptDir.find(item => startPath.indexOf(item) > -1)) {
831
+ return;
832
+ }
833
+
834
+ const files = fs$6.readdirSync(startPath);
835
+ files.forEach(file => {
836
+ const filename = path$3.join(startPath, file);
837
+ const stat = fs$6.lstatSync(filename); // 当前文件是文件夹类型,继续递归
838
+
839
+ if (stat.isDirectory()) {
840
+ find(filename, filter);
841
+ } else if (filename.indexOf(filter) >= 0) {
842
+ // 文件类型
843
+ result.push(filename);
844
+ }
845
+ });
846
+ };
847
+
848
+ find(startPath, filter);
849
+ return result;
850
+ };
851
+ /**
852
+ * 找到项目中所有的package.json文件
853
+ * @param {Array<String>} subRoots 需要安装npm依赖的路径
854
+ * @param {String} contextDir 命令运行的目录
855
+ * @returns {Array<String>} 找到的所有package.json文件的路径
856
+ */
857
+
858
+
859
+ const findAllPackageJson$1 = (subRoots = [], contextDir) => {
860
+ const packageJsonName = 'package.json'; // 查找文件名
861
+
862
+ const cwd = contextDir || dirpath;
863
+ const result = [path$3.join(cwd, packageJsonName)]; // 默认填充根目录下的package.json
864
+
865
+ subRoots.forEach(subRoot => {
866
+ const toppath = path$3.join(cwd, subRoot.root); // 从该目录开始查找package.json文件
867
+
868
+ const list = findFilesByFilter(toppath, packageJsonName);
869
+ result.push(...list);
870
+ });
871
+ return result;
872
+ };
873
+
874
+ var npmUtils = {
875
+ npmInstallAll: npmInstallAll$1,
876
+ findAllPackageJson: findAllPackageJson$1
877
+ };
878
+
879
+ /* eslint-disable require-jsdoc */
880
+ const ci = require$$0__default$4;
881
+ const path$2 = require$$1__default$1;
882
+ /**
883
+ * 获取小程序ci的Project对象
884
+ * @returns {Object} 小程序ci对象
885
+ */
886
+
887
+ const getMpCi = ({
888
+ appId,
889
+ projectPath,
890
+ type = 'miniProgram',
891
+ privateKey = 'TODO'
892
+ }) => {
893
+ var _cfgJsonContent$packO;
894
+
895
+ const cfgJsonContent = require(path$2.join(projectPath, 'project.config.json'));
896
+
897
+ const ignores = (cfgJsonContent === null || cfgJsonContent === void 0 ? void 0 : (_cfgJsonContent$packO = cfgJsonContent.packOptions) === null || _cfgJsonContent$packO === void 0 ? void 0 : _cfgJsonContent$packO.ignore.map(({
898
+ value
899
+ }) => value)) || [];
900
+ return new ci.Project({
901
+ appid: appId,
902
+ privateKey,
903
+ type,
904
+ projectPath,
905
+ ignores: ['node_modules/**/*', ...ignores]
906
+ });
907
+ }; // 用小程序ci工具构建小程序
908
+
909
+
910
+ const packMpProject = async project => {
911
+ await ci.packNpm(project, {
912
+ ignores: ['cloud/**/*']
913
+ });
914
+ };
915
+ /**
916
+ * 格式化构建npm结果信息
917
+ * @param {Array<String>} warning 构建时的告警信息
918
+ * @returns {String} npm构建错误信息
919
+ */
920
+
921
+
922
+ const formatPackNpmWarning = warning => {
923
+ if (!warning) {
924
+ return '';
925
+ }
926
+
927
+ const result = warning.map((it, index) => `${index + 1}. ${it.msg}
928
+ \t@ ${it.jsPath}:${it.tips}`).join('---------------\n');
929
+ return result;
930
+ };
931
+ /**
932
+ * 构建miniprogram_npm
933
+ * @returns {Object} 小程序ci对象
934
+ */
935
+
936
+
937
+ const buildMpNpm$1 = async ({
938
+ appId,
939
+ projectPath,
940
+ privateKey
941
+ }) => {
942
+ const mpCi = await getMpCi({
943
+ appId,
944
+ projectPath,
945
+ privateKey
946
+ });
947
+ const packNpmWarning = await packMpProject(mpCi);
948
+ const packNpmMsg = formatPackNpmWarning(packNpmWarning);
949
+
950
+ if (packNpmMsg) {
951
+ return Promise.reject(packNpmMsg);
952
+ }
953
+
954
+ return Promise.resolve();
955
+ };
956
+
957
+ var mpCiUtils = {
958
+ buildMpNpm: buildMpNpm$1
959
+ };
960
+
961
+ class Globale {
962
+ constructor() {
963
+ this.moduleCache = {};
964
+ }
965
+
966
+ setModuleCache(url, branch, dest) {
967
+ const instance = getGlobalInstance$1();
968
+ const key = `${branch}:${url}`;
969
+ instance.moduleCache[key] = {
970
+ dest
971
+ };
972
+ return instance.moduleCache[key];
973
+ }
974
+
975
+ getModuleCache(url, branch) {
976
+ const instance = getGlobalInstance$1();
977
+ return instance.moduleCache[`${branch}:${url}`];
978
+ }
979
+
980
+ }
981
+
982
+ let instance;
983
+
984
+ function getGlobalInstance$1() {
985
+ if (instance) {
986
+ return instance;
987
+ }
988
+
989
+ return instance = new Globale();
990
+ }
991
+
992
+ var global = {
993
+ getGlobalInstance: getGlobalInstance$1
994
+ };
995
+
996
+ const MetalSmith = require$$0__default$3;
997
+ const {
998
+ getGlobalInstance
999
+ } = global;
1000
+ const {
1001
+ downloadRepoForGit,
1002
+ resolve: resolve$7
1003
+ } = widgets;
1004
+ const {
1005
+ fail: fail$7
1006
+ } = log$2;
1007
+ const fs$5 = require$$1__default$2;
1008
+ const shelljs$3 = require$$5__default;
1009
+ /**
1010
+ * 对克隆下来的模块进行相应的文件处理操作,比如收集处理模块信息,进行信息缓存等操作
1011
+ * @param { string } sourceDir 缓存文件夹
1012
+ * @param { string } targetDir 目标文件夹
1013
+ * @param { arrary } ignore
1014
+ * @returns { undefined } no return
1015
+ */
1016
+
1017
+ function moveFile(sourceDir, targetDir, ignore = []) {
1018
+ // 删除不是文件夹的文件
1019
+ return new Promise(resolve => {
1020
+ MetalSmith(__dirname).ignore(ignore).source(sourceDir).destination(targetDir).build(e => {
1021
+ if (e) {
1022
+ fail$7(e); // eslint-disable-line
1023
+
1024
+ console.log('MetalSmith 详细的错误信息:', e);
1025
+ }
1026
+
1027
+ resolve();
1028
+ });
1029
+ });
1030
+ }
1031
+ /**
1032
+ * 下载目标模块
1033
+ * @param { string } sourceDir 缓存文件夹
1034
+ * @param { string } targetDir 目标文件夹
1035
+ * @returns { array } modules 描述模块的列表
1036
+ */
1037
+
1038
+
1039
+ async function cloneModules$1(sourceDir, targetDir, modules) {
1040
+ // 根据小程序的配置文件下载模块, 并且处理信息
1041
+ for (const moduleInfo of modules) {
1042
+ // eslint-disable-line
1043
+ if (moduleInfo.repoInfo) {
1044
+ await downLoadAndMoveModule(sourceDir, targetDir, moduleInfo);
1045
+ }
1046
+ }
1047
+ }
1048
+ /**
1049
+ * 下载模块信息并且将它移动到对应的位置
1050
+ * @param { string } sourceDir 代码缓存文件夹
1051
+ * @param { string } targetDir 代码要放到的目标文件夹
1052
+ * @returns { array } moduleInfo 描述模块的信息
1053
+ */
1054
+
1055
+
1056
+ async function downLoadAndMoveModule(sourceDir, targetDir, moduleInfo) {
1057
+ const {
1058
+ repoInfo: {
1059
+ buildGitTag,
1060
+ httpRepoUrl
1061
+ },
1062
+ path
1063
+ } = moduleInfo; // 源码临时存在的源目录
1064
+
1065
+ let sourcePath = resolve$7(sourceDir, path); // 源码要放到目标目录
1066
+
1067
+ const targetPath = resolve$7(targetDir, path); // 设置模块的构建分支
1068
+
1069
+ const cloneBranch = buildGitTag && typeof buildGitTag === 'string' ? buildGitTag : 'master'; // 检查缓存中有没有
1070
+
1071
+ const globalInstance = getGlobalInstance();
1072
+ const moduleInCache = globalInstance.getModuleCache(httpRepoUrl, cloneBranch);
1073
+
1074
+ try {
1075
+ if (!moduleInCache) {
1076
+ await downloadRepoForGit(httpRepoUrl, sourcePath, cloneBranch);
1077
+ globalInstance.setModuleCache(httpRepoUrl, cloneBranch, sourcePath);
1078
+ } else {
1079
+ sourcePath = globalInstance.getModuleCache(httpRepoUrl, cloneBranch).dest;
1080
+ }
1081
+
1082
+ if (fs$5.existsSync(targetPath)) {
1083
+ shelljs$3.rm('-rf', targetPath);
1084
+ }
1085
+
1086
+ await moveFile(sourcePath, targetPath, ['node_modules', '.git']);
1087
+ } catch (e) {
1088
+ fail$7(`downLoadAndMoveModule ${e}`); // eslint-disable-line
1089
+
1090
+ process.exit(-1);
1091
+ }
1092
+ }
1093
+
1094
+ var cloneModules_1 = {
1095
+ cloneModules: cloneModules$1
1096
+ };
1097
+
1098
+ var defaultTmsConfig$1 = {
1099
+ // 全局的环境配置项
1100
+ envData: {},
1101
+ // 模块配置信息
1102
+ modules: [],
1103
+ webpack: {
1104
+ /** 编译输出文件夹位置 */
1105
+ outputDir: 'dist',
1106
+
1107
+ /** 源码监听路径 */
1108
+ sourceDir: './',
1109
+
1110
+ /** 源码Map */
1111
+ sourceMap: 'none',
1112
+
1113
+ /** 别名 */
1114
+ alias: {}
1115
+ }
1116
+ };
1117
+
1118
+ const loadash = require$$0__default$5;
1119
+ const fs$4 = require$$1__default$2;
1120
+ const {
1121
+ TMS_NAME: TMS_NAME$1,
1122
+ TMS_CONFIG_FILENAME,
1123
+ MODULE_CONFIG_FILENAME
1124
+ } = require$$3;
1125
+ const {
1126
+ resolve: resolve$6,
1127
+ isObject
1128
+ } = widgets;
1129
+ const {
1130
+ setModuleConfig
1131
+ } = buildAppJson;
1132
+ const defaultTmsConfig = defaultTmsConfig$1;
1133
+ const {
1134
+ fail: fail$6
1135
+ } = log$2;
1136
+ /**
1137
+ * 读取tms.config.json
1138
+ * @param env {string} 环境变量
1139
+ */
1140
+
1141
+ const readTmsConfig$1 = function (env) {
1142
+ const tmsConfigPath = resolve$6(TMS_CONFIG_FILENAME);
1143
+
1144
+ if (!fs$4.existsSync(tmsConfigPath)) {
1145
+ fail$6('当前执行目录没有tms.config.js的配置项,请进行配置');
1146
+ process.exit(1);
1147
+ }
1148
+
1149
+ const tmsConfigFn = require(tmsConfigPath);
1150
+
1151
+ const tmsConfig = tmsConfigFn({
1152
+ env
1153
+ }); // 合并默认值
1154
+
1155
+ loadash.mergeWith(tmsConfig, defaultTmsConfig);
1156
+ return tmsConfig;
1157
+ };
1158
+ /**
1159
+ * 从tms.config.json中检索用户传入的有效modules
1160
+ * @param { object } tmsConfig
1161
+ * @param { array } modules
1162
+ * @returns
1163
+ */
1164
+
1165
+
1166
+ const checkModules$1 = function (tmsConfig, modules) {
1167
+ const targetModules = [];
1168
+ modules.forEach(moduleName => {
1169
+ const module = tmsConfig.modules.find(module => module.name === moduleName);
1170
+ module && targetModules.push(module);
1171
+ });
1172
+
1173
+ if (targetModules.length === 0) {
1174
+ fail$6(`你启动的模块无效,尝试 ${TMS_NAME$1} -m moduleName`);
1175
+ process.exit(1);
1176
+ }
1177
+
1178
+ return targetModules;
1179
+ };
1180
+ /**
1181
+ * tms.config.js的modules 合并 module.config.json的配置项
1182
+ * @param {array} modules
1183
+ * @param {string} appName
1184
+ * @param {string} moduleDir
1185
+ * @returns
1186
+ */
1187
+
1188
+
1189
+ const tmsModulesMergeLocalModuleCfg$3 = (modules, appName, moduleDir) => {
1190
+ const newModules = [];
1191
+ modules.forEach(({
1192
+ path: relativePath,
1193
+ name: moduleName
1194
+ }, moduleIndex) => {
1195
+ const moduleConfigPath = resolve$6(relativePath, MODULE_CONFIG_FILENAME);
1196
+
1197
+ if (fs$4.existsSync(moduleConfigPath)) {
1198
+ let moduleConfigContent = fs$4.readFileSync(moduleConfigPath, 'utf-8');
1199
+ moduleConfigContent = setModuleConfig(moduleConfigContent, appName, moduleDir);
1200
+ const moduleContentArr = isObject(moduleConfigContent) ? [moduleConfigContent] : moduleConfigContent;
1201
+ moduleContentArr.forEach(({
1202
+ name
1203
+ }, moduleContentArrIndex) => {
1204
+ if (name === moduleName) {
1205
+ newModules.push({ ...modules[moduleIndex],
1206
+ ...moduleContentArr[moduleContentArrIndex]
1207
+ });
1208
+ }
1209
+ });
1210
+ } else {
1211
+ newModules.push({ ...modules[moduleIndex]
1212
+ });
1213
+ }
1214
+ });
1215
+ return newModules;
1216
+ };
1217
+
1218
+ var tkitUtils = {
1219
+ readTmsConfig: readTmsConfig$1,
1220
+ checkModules: checkModules$1,
1221
+ tmsModulesMergeLocalModuleCfg: tmsModulesMergeLocalModuleCfg$3
1222
+ };
1223
+
1224
+ const shelljs$2 = require$$5__default;
1225
+ const fs$3 = require$$1__default$2;
1226
+ const io = io$2;
1227
+ const {
1228
+ resolve: resolve$5,
1229
+ createTask: createTask$2
1230
+ } = widgets;
1231
+ const {
1232
+ buildOutputAppJson: buildOutputAppJson$1
1233
+ } = buildAppJson;
1234
+ const {
1235
+ npmInstallAll
1236
+ } = npmUtils;
1237
+ const {
1238
+ buildMpNpm
1239
+ } = mpCiUtils;
1240
+ const {
1241
+ MODULE_CODE_DIR,
1242
+ CACHE_DIR,
1243
+ DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$2,
1244
+ DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR$3
1245
+ } = require$$3;
1246
+ const {
1247
+ cloneModules
1248
+ } = cloneModules_1;
1249
+ const {
1250
+ tmsModulesMergeLocalModuleCfg: tmsModulesMergeLocalModuleCfg$2
1251
+ } = tkitUtils;
1252
+ const {
1253
+ fail: fail$5
1254
+ } = log$2;
1255
+ /**
1256
+ * 拷贝package.json\模块的代码到编译输出目录
1257
+ * @param { object } tmsConfig
1258
+ * @param { array } modules
1259
+ * @param { array } defaultFiles 默认需要拷贝的配置项
1260
+ * @returns
1261
+ */
1262
+
1263
+ const cpFilesToOutput = function (tmsConfig, targetModules, defaultFiles) {
1264
+ const outputDir = resolve$5(tmsConfig.webpack.outputDir);
1265
+ io.ensureDirExist(outputDir);
1266
+ defaultFiles.forEach(item => {
1267
+ if (fs$3.existsSync(resolve$5(item))) {
1268
+ shelljs$2.cp('-rf', resolve$5(item), resolve$5(tmsConfig.webpack.outputDir, item));
1269
+ }
1270
+ }); // 拷贝模块的代码到编译输出目录
1271
+
1272
+ targetModules.forEach(item => {
1273
+ const outputModuleDir = resolve$5(`${tmsConfig.webpack.outputDir}/${item.root}`);
1274
+
1275
+ if (!fs$3.existsSync(resolve$5(item.path))) {
1276
+ fail$5(`${item.path}模块代码路径不存在, 请检查tms.config.js的${item.name}模块的path`);
1277
+ process.exit(1);
1278
+ }
1279
+
1280
+ if (!fs$3.existsSync(outputModuleDir)) {
1281
+ shelljs$2.mkdir('-p', outputModuleDir);
1282
+ } else {
1283
+ // 删除除了node_modules、miniprogram_npm 的其他文件
1284
+ // eslint-disable-next-line
1285
+ shelljs$2.exec('find . -not \( -name node_modules -or -name miniprogram_npm \) -delete', {
1286
+ silent: true
1287
+ });
1288
+ }
1289
+
1290
+ shelljs$2.cp('-Rf', `${resolve$5(item.path)}/*`, outputModuleDir);
1291
+ });
1292
+ };
1293
+
1294
+ async function task(tmsConfig, targetModules) {
1295
+ // 下载和移动代码
1296
+ await createTask$2(cloneModules, '开始下载模块代码完成', '下载模块代码码完成')(MODULE_CODE_DIR, resolve$5('./'), targetModules); // tms.config.js的modules 合并 module.config.json的配置项
1297
+
1298
+ const newModules = tmsModulesMergeLocalModuleCfg$2(targetModules, tmsConfig.appName, DEFAULT_MODULE_DIR$3);
1299
+ console.log('当前init的有效模块', newModules.map(item => item.name)); // 拷贝相关配置文件到输出目录
1300
+
1301
+ await createTask$2(cpFilesToOutput, '开始拷贝文件到编译输出目录', '拷贝文件到编译输出目录完成')(tmsConfig, newModules, DEFAULT_COPY_CONFIG$2); // npm install
1302
+
1303
+ await createTask$2(npmInstallAll, '开始npm install', 'npm install 完成')(newModules, resolve$5(tmsConfig.webpack.outputDir), `${CACHE_DIR}/node_modules`); // 构建miniprograme_npm
1304
+
1305
+ await createTask$2(buildMpNpm, '开始构建miniprograme_npm', '构建miniprograme_npm 完成')({
1306
+ appId: tmsConfig.appId,
1307
+ projectPath: resolve$5('./'),
1308
+ privateKey: tmsConfig.privateKey
1309
+ }); // 动态生成编译后的app.json;
1310
+
1311
+ await createTask$2(buildOutputAppJson$1, '开始生成编译后的app.json', '生成编译后的app.json完成')(tmsConfig, newModules);
1312
+ return newModules;
1313
+ }
1314
+
1315
+ async function bootstrap(tmsConfig, targetModules) {
1316
+ const newModules = await task(tmsConfig, targetModules);
1317
+ return {
1318
+ targetModules: newModules
1319
+ };
1320
+ }
1321
+
1322
+ var init$5 = bootstrap;
1323
+
1324
+ const path$1 = require$$1__default$1;
1325
+ const fs$2 = require$$1__default$2;
1326
+ const {
1327
+ resolve: resolve$4
1328
+ } = widgets;
1329
+ const {
1330
+ buildOutputAppJson
1331
+ } = buildAppJson;
1332
+ const {
1333
+ tmsModulesMergeLocalModuleCfg: tmsModulesMergeLocalModuleCfg$1
1334
+ } = tkitUtils;
1335
+ const {
1336
+ findAllPackageJson
1337
+ } = npmUtils;
1338
+ const {
1339
+ fail: fail$4
1340
+ } = log$2;
1341
+ const replaceExt = require$$7__default;
1342
+ const extensions = ['.ts', '.js'];
1343
+
1344
+ function ext(entry, extensions) {
1345
+ let newEntry = entry;
1346
+
1347
+ try {
1348
+ const stat = fs$2.lstatSync(newEntry);
1349
+
1350
+ if (stat.isDirectory()) {
1351
+ newEntry += newEntry[newEntry.length - 1] === '/' ? 'index' : '/index';
1352
+ }
1353
+ } catch (e) {}
1354
+
1355
+ for (const ext of extensions) {
1356
+ const file = replaceExt(newEntry, ext);
1357
+
1358
+ if (fs$2.existsSync(file)) {
1359
+ return {
1360
+ file,
1361
+ ext
1362
+ };
1363
+ }
1364
+ }
1365
+
1366
+ return null;
1367
+ } // 获取所有的package.json里的依赖包Dir
1368
+
1369
+
1370
+ function getAlias$1(modules) {
1371
+ const alias = {};
1372
+ const allPackages = findAllPackageJson(modules, resolve$4('./dist'));
1373
+ allPackages.forEach(packageFilePath => {
1374
+ const {
1375
+ dependencies
1376
+ } = require(packageFilePath);
1377
+
1378
+ Object.keys(dependencies).forEach(dependence => {
1379
+ alias[dependence] = path$1.join(path$1.dirname(packageFilePath), `./miniprogram_npm/${dependence}`);
1380
+ });
1381
+ });
1382
+ return alias;
1383
+ } // 根据用户选择的modules,找到module.config.json的配置信息,找到所有的page
1384
+
1385
+
1386
+ function getPageEntry(modules, tmsConfig, moduleDir) {
1387
+ const entry = {}; // tms.config.js的modules 合并 module.config.json的配置项
1388
+
1389
+ const newModules = tmsModulesMergeLocalModuleCfg$1(modules, tmsConfig.appName, moduleDir);
1390
+ newModules.forEach(({
1391
+ path: relativePath,
1392
+ pages,
1393
+ root
1394
+ }) => {
1395
+ pages.forEach(page => {
1396
+ const pageJsonPath = `${resolve$4(relativePath, page)}.json`;
1397
+
1398
+ if (fs$2.existsSync(pageJsonPath)) {
1399
+ const pageJsonContent = JSON.parse(fs$2.readFileSync(pageJsonPath, 'utf-8'));
1400
+ const pageDir = path$1.dirname(pageJsonPath); // 该页面所在的目录
1401
+
1402
+ const extValue = ext(resolve$4(relativePath, page), extensions);
1403
+
1404
+ if (!extValue) {
1405
+ fail$4(`当前${page}找不到入口.js或.ts文件`);
1406
+ process.exit(1);
1407
+ }
1408
+
1409
+ const entryKey = `${root}/${page}${extValue.ext}`;
1410
+ Object.assign(entry, {
1411
+ [entryKey]: extValue.file
1412
+ }, getComponentEntry(pageJsonContent, pageDir, path$1.dirname(entryKey)));
1413
+ }
1414
+ });
1415
+ });
1416
+ return entry;
1417
+ } // 根据appJson,获取所有的page
1418
+
1419
+
1420
+ function getEntry$2(defaultWebpackEntry, modules, tmsConfig, moduleDir) {
1421
+ const defaultEntry = {};
1422
+ Object.keys(defaultWebpackEntry).forEach(key => {
1423
+ const extValue = ext(defaultWebpackEntry[key], extensions);
1424
+ defaultEntry[key + extValue.ext] = extValue.file;
1425
+ });
1426
+ return { ...defaultEntry,
1427
+ ...getPageEntry(modules, tmsConfig, moduleDir)
1428
+ };
1429
+ } // 根据pageJson,filePath,获取页面引入的所有component
1430
+
1431
+
1432
+ function getComponentEntry(pageJson, pagePath, pageKey) {
1433
+ const componentEntry = {};
1434
+
1435
+ function task(json, dir, rootKey) {
1436
+ if (!json.usingComponents) {
1437
+ return;
1438
+ }
1439
+
1440
+ const componentKeys = Object.keys(json.usingComponents); // 如果存在依赖的组件
1441
+
1442
+ componentKeys.forEach(key => {
1443
+ if (json.usingComponents[key].startsWith('.')) {
1444
+ // 拼出组件所在位置的绝对路径
1445
+ const comValue = path$1.join(dir, json.usingComponents[key]);
1446
+ const extValue = ext(comValue, extensions);
1447
+ const comKey = path$1.resolve('/', rootKey, json.usingComponents[key]);
1448
+
1449
+ if (!extValue) {
1450
+ fail$4(`当前page: ${pagePath} component: ${comValue}找不到入口.js或.ts文件`);
1451
+ process.exit(1);
1452
+ }
1453
+
1454
+ componentEntry[`${comKey.slice(1)}${extValue.ext}`] = extValue.file;
1455
+ const comJsonPath = `${comValue}.json`;
1456
+
1457
+ if (fs$2.existsSync(comJsonPath)) {
1458
+ const comJsonContent = JSON.parse(fs$2.readFileSync(comJsonPath, 'utf-8'));
1459
+ const comDir = path$1.dirname(comJsonPath); // 该页面所在的目录
1460
+
1461
+ task(comJsonContent, comDir, path$1.dirname(comKey));
1462
+ }
1463
+ }
1464
+ });
1465
+ }
1466
+
1467
+ task(pageJson, pagePath, pageKey);
1468
+ return componentEntry;
1469
+ } // 根据modules处理需要拷贝的模块,copy-webpack-plugin需要的参数
1470
+
1471
+
1472
+ function getCopyPlugin$2(defaultCopyConfig, modules, tmsConfig, env) {
1473
+ const toPath = tmsConfig.webpack.outputDir;
1474
+
1475
+ function generatorAppJson(tmsConfig, modules) {
1476
+ try {
1477
+ return buildOutputAppJson(tmsConfig, modules);
1478
+ } catch (e) {
1479
+ fail$4(`动态生成app.json出现错误${e} 请检查你的配置项`);
1480
+ return {};
1481
+ }
1482
+ }
1483
+
1484
+ const patterns = []; // 默认的一些配置拷贝文件 package.json、sitemap.json等
1485
+
1486
+ defaultCopyConfig.forEach(item => {
1487
+ if (fs$2.existsSync(resolve$4(item))) {
1488
+ patterns.push({
1489
+ from: resolve$4(item),
1490
+ to: resolve$4(`./${toPath}/${item}`),
1491
+ transform: {
1492
+ cache: true
1493
+ }
1494
+ });
1495
+ }
1496
+ }); // 拷贝模块的代码
1497
+
1498
+ modules.forEach(item => {
1499
+ patterns.push({
1500
+ from: resolve$4(item.path),
1501
+ to: resolve$4(`./${toPath}/${item.root}`),
1502
+ globOptions: {
1503
+ ignore: ['**/*.js', '*.js', '**/*.ts', '*.ts']
1504
+ },
1505
+ transform: {
1506
+ cache: true,
1507
+ transformer: env === 'dev' ? (content, absoluteFrom) => {
1508
+ // 监听module.config.json的修改, 自动生成编译后的app.json
1509
+ if (absoluteFrom.indexOf('module.config.json') > -1) {
1510
+ generatorAppJson(tmsConfig, modules);
1511
+ }
1512
+
1513
+ return content;
1514
+ } : content => content
1515
+ }
1516
+ });
1517
+ });
1518
+
1519
+ if (env === 'dev') {
1520
+ // 拷贝app.json时,自动生成编译后的app.json
1521
+ const appJsonConfig = ['app.json'];
1522
+ appJsonConfig.forEach(item => {
1523
+ patterns.push({
1524
+ from: resolve$4(item),
1525
+ to: resolve$4(`./${toPath}/${item}`),
1526
+ transform: {
1527
+ cache: true,
1528
+ transformer: () => {
1529
+ const appJson = generatorAppJson(tmsConfig, modules);
1530
+ return JSON.stringify(appJson, null, 2);
1531
+ }
1532
+ }
1533
+ });
1534
+ });
1535
+ }
1536
+
1537
+ return patterns;
1538
+ } // dev时,给webpack注入相应的事件
1539
+
1540
+
1541
+ const setupDevWebPackHooks$1 = (context, firstDone) => {
1542
+ let tempFirstDone = true;
1543
+
1544
+ const invalid = () => {
1545
+ // eslint-disable-next-line
1546
+ context.stats = undefined;
1547
+ };
1548
+
1549
+ const done = stats => {
1550
+ // eslint-disable-next-line
1551
+ context.stats = stats;
1552
+ process.nextTick(() => {
1553
+ const {
1554
+ stats
1555
+ } = context;
1556
+ if (!stats) return;
1557
+
1558
+ if (tempFirstDone) {
1559
+ tempFirstDone = false;
1560
+ firstDone();
1561
+ }
1562
+ });
1563
+ };
1564
+
1565
+ const {
1566
+ compiler
1567
+ } = context;
1568
+ compiler.hooks.watchRun.tap('miniprogram-dev', invalid);
1569
+ compiler.hooks.invalid.tap('miniprogram-dev', invalid);
1570
+ compiler.hooks.done.tap('miniprogram-dev', done);
1571
+ };
1572
+
1573
+ const stringified$1 = raw => ({
1574
+ 'process.env': Object.keys(raw).reduce((env, key) => {
1575
+ // eslint-disable-next-line
1576
+ env[key] = JSON.stringify(raw[key]);
1577
+ return env;
1578
+ }, {})
1579
+ });
1580
+
1581
+ var utils = {
1582
+ getCopyPlugin: getCopyPlugin$2,
1583
+ setupDevWebPackHooks: setupDevWebPackHooks$1,
1584
+ getEntry: getEntry$2,
1585
+ stringified: stringified$1,
1586
+ getAlias: getAlias$1
1587
+ };
1588
+
1589
+ const WebpackChain = require$$0__default$6;
1590
+ const webpack$2 = require$$0__default$7;
1591
+ const {
1592
+ getEntry: getEntry$1,
1593
+ stringified,
1594
+ getAlias
1595
+ } = utils;
1596
+ const {
1597
+ resolve: resolve$3
1598
+ } = widgets;
1599
+ const {
1600
+ DEFAULT_WEBPACK_ENTRY: DEFAULT_WEBPACK_ENTRY$1,
1601
+ DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR$2
1602
+ } = require$$3;
1603
+
1604
+ var base = (tmsConfig, modules) => {
1605
+ const {
1606
+ envData = {},
1607
+ webpack: tmsWebpack
1608
+ } = tmsConfig;
1609
+ let webpackConfig = new WebpackChain();
1610
+ const alias = getAlias(modules);
1611
+ const entry = getEntry$1(DEFAULT_WEBPACK_ENTRY$1, modules, tmsConfig, DEFAULT_MODULE_DIR$2);
1612
+ webpackConfig.merge({
1613
+ entry,
1614
+ output: {
1615
+ path: resolve$3(`./${tmsWebpack.outputDir}`),
1616
+ libraryTarget: 'commonjs2',
1617
+ filename: '[name]'
1618
+ },
1619
+ // TODO 有报错,先注释掉
1620
+ // cache: {
1621
+ // type: 'filesystem',
1622
+ // cacheDirectory: resolve(`./${tmsConfig.webpack.outputDir}/node_modules/.cache`),
1623
+ // },
1624
+ resolve: {
1625
+ extensions: ['.tsx', '.ts', '.js'],
1626
+ alias: Object.assign(tmsWebpack.alias, alias)
1627
+ },
1628
+ devtool: tmsWebpack.sourceMap ? 'source-map' : false
1629
+ });
1630
+ webpackConfig.module.rule('ts-loader').test(/\.ts$/).use('ts-loader').loader(require.resolve('ts-loader')).options({
1631
+ configFile: resolve$3('./tsconfig.json'),
1632
+ // 只进行语法转换,不进行类型校验,提高构建速度
1633
+ transpileOnly: true
1634
+ }).end(); // webpackConfig.module
1635
+ // .rule('babel')
1636
+ // .test(/\.(js|mjs|jsx|ts|tsx)$/)
1637
+ // .pre()
1638
+ // .exclude.add(/(node_modules|miniprogram_npm)/).end()
1639
+ // .use(require.resolve('babel-loader'))
1640
+ // .loader(require.resolve('babel-loader'));
1641
+
1642
+ webpackConfig.plugin('definePlugin').use(webpack$2.DefinePlugin, [stringified(envData)]).end(); // 执行tms.config.js自定义的webpackChain
1643
+
1644
+ if (tmsWebpack.webpackChain) {
1645
+ webpackConfig = tmsWebpack.webpackChain(webpackConfig, {
1646
+ modules
1647
+ });
1648
+ }
1649
+
1650
+ return webpackConfig;
1651
+ };
1652
+
1653
+ const SingleEntryPlugin = require$$0__default$8;
1654
+ const {
1655
+ DEFAULT_WEBPACK_ENTRY,
1656
+ DEFAULT_MODULE_DIR: DEFAULT_MODULE_DIR$1
1657
+ } = require$$3;
1658
+ const {
1659
+ getEntry
1660
+ } = utils;
1661
+
1662
+ class EntryExtraPlugin {
1663
+ constructor(options = {}) {
1664
+ this.options = options;
1665
+ this.scriptExtensions = options.scriptExtensions || ['.ts', '.js'];
1666
+ }
1667
+
1668
+ applyEntry(compiler, entry) {
1669
+ const {
1670
+ context
1671
+ } = compiler.options;
1672
+ Object.keys(entry).forEach(key => {
1673
+ new SingleEntryPlugin(context, entry[key], key).apply(compiler);
1674
+ });
1675
+ }
1676
+
1677
+ apply(compiler) {
1678
+ const {
1679
+ tmsConfig = {},
1680
+ modules = []
1681
+ } = this.options;
1682
+ compiler.hooks.watchRun.tap('EntryExtraPlugin', () => {
1683
+ const entry = getEntry(DEFAULT_WEBPACK_ENTRY, modules, tmsConfig, DEFAULT_MODULE_DIR$1);
1684
+ this.applyEntry(compiler, entry);
1685
+ });
1686
+ }
1687
+
1688
+ }
1689
+
1690
+ var entryExtractPlugin = EntryExtraPlugin;
1691
+
1692
+ const webpackConfig$1 = base;
1693
+ const {
1694
+ DEFAULT_COPY_CONFIG: DEFAULT_COPY_CONFIG$1
1695
+ } = require$$3;
1696
+ const {
1697
+ getCopyPlugin: getCopyPlugin$1
1698
+ } = utils;
1699
+
1700
+ var dev$2 = (...args) => {
1701
+ const [tmsConfig, modules] = args;
1702
+ const webpackDevConfig = webpackConfig$1(...args);
1703
+ webpackDevConfig.devtool('source-map');
1704
+ webpackDevConfig.mode('development');
1705
+ const copyPluginParams = getCopyPlugin$1(DEFAULT_COPY_CONFIG$1, modules, tmsConfig, 'dev'); // console.log('copyPluginParams', copyPluginParams);
1706
+
1707
+ webpackDevConfig.plugin('copy-webpack-plugin').use(require$$3__default, [{
1708
+ patterns: copyPluginParams
1709
+ }]).end();
1710
+ webpackDevConfig.plugin('ExtractPlugin').use(entryExtractPlugin, [{
1711
+ tmsConfig,
1712
+ modules
1713
+ }]).end();
1714
+ return webpackDevConfig;
1715
+ };
1716
+
1717
+ const webpack$1 = require$$0__default$7;
1718
+ const webDevConfig = dev$2;
1719
+ const {
1720
+ setupDevWebPackHooks
1721
+ } = utils;
1722
+ const {
1723
+ fail: fail$3
1724
+ } = log$2;
1725
+
1726
+ var devServer = (...args) => {
1727
+ const config = webDevConfig(...args);
1728
+ const compiler = webpack$1(config.toConfig());
1729
+ setupDevWebPackHooks({
1730
+ compiler
1731
+ }, () => {// TODO 判断open参数,打开微信开发者工具
1732
+ // openDevtool(api.resolve(config.outputDir || 'dist'))
1733
+ });
1734
+ compiler.watch({
1735
+ aggregateTimeout: 1000,
1736
+ poll: undefined
1737
+ }, (err, stats) => {
1738
+ if (err) {
1739
+ fail$3(err);
1740
+ console.log('详细的错误信息:', err);
1741
+ }
1742
+
1743
+ if (stats.hasErrors() || stats.hasWarnings()) {
1744
+ console.log(stats.toString({
1745
+ // 增加控制台颜色开关
1746
+ colors: true
1747
+ }));
1748
+ }
1749
+ });
1750
+ return compiler;
1751
+ };
1752
+
1753
+ const fs$1 = require$$1__default$2;
1754
+ const semver$1 = require$$1__default$5;
1755
+ const {
1756
+ resolve: resolve$2
1757
+ } = widgets;
1758
+ const path = require$$1__default$1;
1759
+ const {
1760
+ fail: fail$2
1761
+ } = log$2;
1762
+ const shelljs$1 = require$$5__default;
1763
+
1764
+ const getLatestVersion = npmName => {
1765
+ const data = shelljs$1.exec(`npm view ${npmName} version`);
1766
+ return data.stdout || '0.0.0';
1767
+ };
1768
+ /**
1769
+ * 检查package.json的依赖大于node_module的版本,则返回true
1770
+ * @param {*} modules 模块
1771
+ * @param {*} cwd 待检查package.json所在的目录 (eg: 当前执行脚本的目录)
1772
+ * @param {*} outputDir 待检查node_modules存放的目录 (eg: dist/node_modules)
1773
+ * @returns
1774
+ */
1775
+
1776
+
1777
+ const checkDependencies$1 = (modules, cwd, outputDir) => {
1778
+ // 步骤1. 收集package.json
1779
+ const packageJsonName = 'package.json'; // 查找文件名
1780
+ // 1.1根目录的package.json
1781
+
1782
+ const packageArr = [{
1783
+ srcPackageDir: path.join(cwd, packageJsonName),
1784
+ destNpmDir: resolve$2(outputDir, 'node_modules')
1785
+ }]; // 1.2模块的package.json
1786
+
1787
+ modules.forEach(item => {
1788
+ const srcPackageDir = path.join(cwd, item.path, 'package.json');
1789
+
1790
+ if (fs$1.existsSync(srcPackageDir)) {
1791
+ packageArr.push({
1792
+ srcPackageDir,
1793
+ destNpmDir: resolve$2(outputDir, item.root, 'node_modules')
1794
+ });
1795
+ }
1796
+ }); // 步骤2. 比较package.json的依赖与node_modules依赖的版本号
1797
+
1798
+ for (const item of packageArr) {
1799
+ const packageJson = fs$1.readFileSync(item.srcPackageDir, 'utf-8');
1800
+ let dependencies;
1801
+
1802
+ try {
1803
+ dependencies = JSON.parse(packageJson).dependencies;
1804
+ } catch (e) {
1805
+ fail$2(`解析${packageJson}报错,请检查是否是正确的json配置项`);
1806
+ process.exit(1);
1807
+ }
1808
+
1809
+ const dependenciesKeys = Object.keys(dependencies);
1810
+
1811
+ for (const key of dependenciesKeys) {
1812
+ const depPath = path.join(item.destNpmDir, key);
1813
+
1814
+ if (!fs$1.existsSync(depPath)) {
1815
+ return true;
1816
+ }
1817
+
1818
+ const depPackagePath = path.join(depPath, 'package.json');
1819
+
1820
+ if (fs$1.existsSync(depPackagePath)) {
1821
+ const packageData = require(depPackagePath);
1822
+
1823
+ if (dependencies[key] === 'latest') {
1824
+ dependencies[key] = getLatestVersion(key);
1825
+ }
1826
+
1827
+ if (packageData.version === 'latest') {
1828
+ packageData.version = getLatestVersion(key);
1829
+ }
1830
+
1831
+ if (semver$1.lt(packageData.version, semver$1.minVersion(dependencies[key]).version)) {
1832
+ return true;
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+
1838
+ return false;
1839
+ };
1840
+
1841
+ var checkDependencies_1 = {
1842
+ checkDependencies: checkDependencies$1
1843
+ };
1844
+
1845
+ const webpackServer = devServer;
1846
+ const fs = require$$1__default$2;
1847
+ const {
1848
+ resolve: resolve$1
1849
+ } = widgets;
1850
+ const init$4 = init$5;
1851
+ const {
1852
+ DEFAULT_MODULE_DIR
1853
+ } = require$$3;
1854
+ const {
1855
+ tmsModulesMergeLocalModuleCfg
1856
+ } = tkitUtils;
1857
+ const {
1858
+ checkDependencies
1859
+ } = checkDependencies_1;
1860
+ const {
1861
+ fail: fail$1
1862
+ } = log$2;
1863
+
1864
+ function isInit(tmsConfig, targetModules, contextDir) {
1865
+ // 判断是否存在dist目录
1866
+ if (!fs.existsSync(contextDir)) {
1867
+ return true;
1868
+ } // 判断dist是否存在node_modules
1869
+
1870
+
1871
+ if (!fs.existsSync(`${contextDir}/node_modules`)) {
1872
+ return true;
1873
+ } // 判断dist是否存在miniprogram_npm
1874
+
1875
+
1876
+ if (!fs.existsSync(`${contextDir}/miniprogram_npm`)) {
1877
+ return true;
1878
+ } // 判断dist是否存在app.json
1879
+
1880
+
1881
+ if (!fs.existsSync(`${contextDir}/app.json`)) {
1882
+ return true;
1883
+ } // 判断\源码\dist\是否存在用户指定的模块
1884
+
1885
+
1886
+ for (const item of targetModules) {
1887
+ // 此模块没有root字段(原因:没有merge到module.config.json的配置项。第三方模块的代码可能还没有下载)
1888
+ if (!item.root) {
1889
+ return true;
1890
+ } // 判断编译目录是否有该模块
1891
+
1892
+
1893
+ if (!fs.existsSync(`${contextDir}/${item.root}`)) {
1894
+ return true;
1895
+ } // 判断源码目录是否有该模块
1896
+
1897
+
1898
+ if (item.path && !fs.existsSync(resolve$1(item.path))) {
1899
+ fail$1(`${item.path}模块代码路径不存在, 请检查tms.config.js的${item.name}模块的path`);
1900
+ process.exit(1);
1901
+ }
1902
+ } // 判断package.json的版本是否有新的版本
1903
+
1904
+
1905
+ return checkDependencies(targetModules, resolve$1('./'), tmsConfig.webpack.outputDir);
1906
+ }
1907
+
1908
+ async function dev$1(tmsConfig, targetModules, env) {
1909
+ // tms.config.js的modules 合并 module.config.json的配置项
1910
+ let newModules = tmsModulesMergeLocalModuleCfg(targetModules, tmsConfig.appName, DEFAULT_MODULE_DIR); // 判断是否进行init命令
1911
+
1912
+ if (isInit(tmsConfig, newModules, resolve$1('dist'))) {
1913
+ // init函数会将 最新的tms.config.js的modules 合并 module.config.json的配置项 返回,不需要再做重复工作
1914
+ const initData = await init$4(tmsConfig, targetModules);
1915
+ newModules = initData.targetModules;
1916
+ }
1917
+
1918
+ console.log('当前dev启动的有效模块', newModules.map(item => item.name));
1919
+ webpackServer(tmsConfig, newModules, env);
1920
+ }
1921
+
1922
+ var dev_1 = dev$1;
1923
+
1924
+ const webpackConfig = base;
1925
+ const {
1926
+ DEFAULT_COPY_CONFIG
1927
+ } = require$$3;
1928
+ const {
1929
+ getCopyPlugin
1930
+ } = utils;
1931
+
1932
+ var build$2 = (...args) => {
1933
+ const [tmsConfig, modules] = args;
1934
+ const webpackBuildConfig = webpackConfig(...args);
1935
+ webpackBuildConfig.mode('production');
1936
+ const copyPluginParams = getCopyPlugin(DEFAULT_COPY_CONFIG, modules, tmsConfig, 'build'); // console.log('copyPluginParams', copyPluginParams);
1937
+
1938
+ webpackBuildConfig.plugin('copy-webpack-plugin').use(require$$3__default, [{
1939
+ patterns: copyPluginParams
1940
+ }]).end();
1941
+ return webpackBuildConfig;
1942
+ };
1943
+
1944
+ const webpack = require$$0__default$7;
1945
+ const webBuildConfig = build$2;
1946
+ const {
1947
+ createTask: createTask$1
1948
+ } = widgets;
1949
+ const {
1950
+ fail
1951
+ } = log$2;
1952
+
1953
+ function compilerRun(compiler) {
1954
+ return new Promise(resolve => {
1955
+ compiler.run((err, stats) => {
1956
+ resolve({
1957
+ err,
1958
+ stats
1959
+ });
1960
+ });
1961
+ });
1962
+ }
1963
+
1964
+ var buildServer = async (...args) => {
1965
+ const config = webBuildConfig(...args);
1966
+ const compiler = webpack(config.toConfig());
1967
+ const {
1968
+ err,
1969
+ stats
1970
+ } = await createTask$1(compilerRun, '开始webpack打包编译', 'webpack打包编译完成')(compiler);
1971
+
1972
+ if (err) {
1973
+ fail(err);
1974
+ console.log('详细的错误信息:', err);
1975
+ }
1976
+
1977
+ if (stats.hasErrors() || stats.hasWarnings()) {
1978
+ console.log(stats.toString({
1979
+ // 增加控制台颜色开关
1980
+ colors: true,
1981
+ errorDetails: true
1982
+ }));
1983
+ }
1984
+ return compiler;
1985
+ };
1986
+
1987
+ const shelljs = require$$5__default;
1988
+ const webpackBuildServer = buildServer;
1989
+ const {
1990
+ resolve
1991
+ } = widgets;
1992
+ const init$3 = init$5;
1993
+
1994
+ async function build$1(tmsConfig, targetModules, env) {
1995
+ // 开始构建前,清理输出目录
1996
+ await shelljs.rm('-rf', resolve('dist'));
1997
+ const {
1998
+ targetModules: newModules
1999
+ } = await init$3(tmsConfig, targetModules);
2000
+ webpackBuildServer(tmsConfig, newModules, env);
2001
+ }
2002
+
2003
+ var build_1 = build$1;
2004
+
2005
+ const init$2 = init$5;
2006
+ const dev = dev_1;
2007
+ const build = build_1;
2008
+ const {
2009
+ createTask
2010
+ } = widgets;
2011
+ const {
2012
+ MODE
2013
+ } = require$$3;
2014
+ const {
2015
+ readTmsConfig,
2016
+ checkModules
2017
+ } = tkitUtils;
2018
+
2019
+ const handleModulesArg = cmd => {
2020
+ // 主模块开发
2021
+ if (cmd.module === MODE.main) {
2022
+ return MODE.main;
2023
+ } // 单模块 或 多模块开发
2024
+
2025
+
2026
+ if (cmd.module) {
2027
+ return [cmd.module, ...cmd.args];
2028
+ } // 全量模块
2029
+
2030
+
2031
+ return MODE.all;
2032
+ };
2033
+
2034
+ async function run(commandName, cmd) {
2035
+ const moduleArg = handleModulesArg(cmd);
2036
+ const {
2037
+ env
2038
+ } = cmd;
2039
+ const tmsConfig = await createTask(readTmsConfig, '开始读取脚手架的配置项', '读取脚手架的配置项完成')(env);
2040
+ let modules; // 主模块
2041
+
2042
+ if (moduleArg === MODE.main) {
2043
+ modules = checkModules(tmsConfig, [...new Set([...tmsConfig.mainPackages])]);
2044
+ } else if (moduleArg === MODE.all) {
2045
+ // 全量模块
2046
+ modules = tmsConfig.modules;
2047
+ } else {
2048
+ // 检查用户输入modules的有效性
2049
+ modules = checkModules(tmsConfig, [...new Set([...tmsConfig.mainPackages, ...moduleArg])]);
2050
+ }
2051
+
2052
+ switch (commandName) {
2053
+ case 'init':
2054
+ init$2(tmsConfig, modules, env);
2055
+ return;
2056
+
2057
+ case 'dev':
2058
+ dev(tmsConfig, modules, env);
2059
+ return;
2060
+
2061
+ case 'build':
2062
+ build(tmsConfig, modules, env);
2063
+ return;
2064
+
2065
+ default:
2066
+ return;
2067
+ }
2068
+ }
2069
+
2070
+ var run_1 = run;
2071
+
2072
+ var entry = [{
2073
+ command: 'create <app-name>',
2074
+ description: '创建新的应用',
2075
+ action: (appName, cmd) => {
2076
+ create_1(appName, cmd);
2077
+ }
2078
+ }, {
2079
+ command: 'run <command-name>',
2080
+ options: [['-m, --module [moduleName]', '模块名称'], ['-e, --env [env]', '环境变量']],
2081
+ description: '运行模块',
2082
+ action: (commandName, cmd) => {
2083
+ run_1(commandName, cmd);
2084
+ }
2085
+ }];
2086
+
2087
+ var require$$6 = {
2088
+ name: "@tmsfe/tmskit",
2089
+ version: "0.0.1",
2090
+ description: "tmskit",
2091
+ main: "main.js",
2092
+ bin: {
2093
+ tmskit: "main.js"
2094
+ },
2095
+ scripts: {
2096
+ dev: "rollup -wc --environment TARGET:tmskit",
2097
+ build: "rollup -c --environment TARGET:tmskit"
2098
+ },
2099
+ author: "tms·web",
2100
+ license: "ISC",
2101
+ buildOptions: {
2102
+ formats: [
2103
+ "cjs"
2104
+ ]
2105
+ },
2106
+ devDependencies: {
2107
+ "@babel/core": "^7.15.0",
2108
+ "@babel/plugin-transform-modules-commonjs": "^7.16.0",
2109
+ "@babel/preset-env": "^7.16.0",
2110
+ "@rollup/plugin-babel": "^5.0.2",
2111
+ "@rollup/plugin-commonjs": "^19.0.0",
2112
+ "@rollup/plugin-dynamic-import-vars": "^1.1.1",
2113
+ "@rollup/plugin-json": "^4.0.3",
2114
+ async: "^3.2.2",
2115
+ "babel-core": "^6.26.3",
2116
+ "babel-loader": "^8.2.3",
2117
+ "copy-webpack-plugin": "^9.1.0",
2118
+ "cross-env": "^7.0.3",
2119
+ leven: "3.1.0",
2120
+ metalsmith: "^2.3.0",
2121
+ minimist: "^1.2.5",
2122
+ rollup: "^2.6.1",
2123
+ "rollup-plugin-node-resolve": "^5.2.0",
2124
+ "rollup-plugin-terser": "^6.1.0",
2125
+ "rollup-plugin-typescript2": "0.27.0",
2126
+ "ts-loader": "^9.2.6",
2127
+ "url-loader": "^4.1.1",
2128
+ webpack: "^5.64.0",
2129
+ "webpack-cli": "^4.9.1"
2130
+ },
2131
+ dependencies: {
2132
+ axios: "^0.21.4",
2133
+ chalk: "^4.1.0",
2134
+ commander: "^6.2.1",
2135
+ "download-git-repo": "^3.0.2",
2136
+ ejs: "^3.1.5",
2137
+ "file-loader": "^6.2.0",
2138
+ "fs-extra": "^9.0.1",
2139
+ inquirer: "^7.3.3",
2140
+ lodash: "^4.17.21",
2141
+ "mini-css-extract-plugin": "^2.4.5",
2142
+ "miniprogram-ci": "1.4.13",
2143
+ ora: "^5.1.0",
2144
+ "replace-ext": "^2.0.0",
2145
+ "rollup-plugin-replace": "^2.2.0",
2146
+ shelljs: "^0.8.4",
2147
+ tslib: "^1.14.1",
2148
+ typescript: "^3.8.3",
2149
+ username: "5.1.0",
2150
+ "webpack-chain": "^6.5.1"
2151
+ },
2152
+ engines: {
2153
+ node: "^12.17.0 || >= 14.0.0"
2154
+ },
2155
+ jest: {
2156
+ testEnvironment: "jest-environment-node"
2157
+ }
2158
+ };
2159
+
2160
+ const {
2161
+ exec
2162
+ } = require$$5__default;
2163
+ const semver = require$$1__default$5;
2164
+ const packageJson = require$$6;
2165
+ const chalk$1 = require$$0__default$1;
2166
+ const {
2167
+ log: log$1
2168
+ } = widgets;
2169
+ const requiredVersion = packageJson.engines.node;
2170
+ const packName = packageJson.name;
2171
+ /**
2172
+ * 检查node版本
2173
+ * @param {String} wanted 希望的node版本
2174
+ * @param {String} id 某node特性
2175
+ * @returns {Undefined} 无需返回值
2176
+ */
2177
+
2178
+ const checkNodeVersion = (wanted, id) => {
2179
+ if (!semver.satisfies(process.version, wanted, {
2180
+ includePrerelease: true
2181
+ })) {
2182
+ log$1(chalk$1.red(`你正在使用的Node版本: ${process.version}, 但是此版本的 ${id} 需要的Node最小版本 ${wanted}.\n请先升级你的Node版本.`));
2183
+ process.exit(1);
2184
+ }
2185
+ };
2186
+ /**
2187
+ * 检查运行环境
2188
+ * @returns {Undefined} 无需返回值
2189
+ */
2190
+
2191
+
2192
+ function initCliContext() {
2193
+ // 执行操作前检查node版本
2194
+ // 旧版本node直接提示升级,退出脚本
2195
+ checkNodeVersion(requiredVersion, packName); // 执行前配置正确的npm源
2196
+
2197
+ exec('npm config set registry https://mirrors.tencent.com/npm/ --global', {
2198
+ silent: true
2199
+ });
2200
+ }
2201
+
2202
+ var init$1 = initCliContext;
2203
+
2204
+ const chalk = require$$0__default$1;
2205
+ const program = require$$0__default;
2206
+ const {
2207
+ log,
2208
+ suggestCommands
2209
+ } = widgets;
2210
+ const {
2211
+ TMS_NAME
2212
+ } = require$$3;
2213
+ const commands = entry;
2214
+ const init = init$1;
2215
+ init();
2216
+ program.version(`${TMS_NAME} ${require$$6.version}`);
2217
+ commands.forEach(cmd => {
2218
+ var _cmd$options;
2219
+
2220
+ const command = program.command(cmd.command);
2221
+ cmd.usage && command.usage(cmd.usage);
2222
+ cmd.description && command.description(cmd.description);
2223
+ (_cmd$options = cmd.options) === null || _cmd$options === void 0 ? void 0 : _cmd$options.forEach(opt => command.option(...opt));
2224
+ command.action(cmd.action);
2225
+ });
2226
+ program.on('--help', () => {
2227
+ log();
2228
+ log(` Run ${chalk.cyan('tms <command> --help')} for detailed usage of given command.`);
2229
+ log();
2230
+ }); // 捕获未注册的命令
2231
+
2232
+ program.arguments('<command>').action(cmd => {
2233
+ program.outputHelp();
2234
+ log(` ${chalk.red(`Unknown command ${chalk.yellow(cmd)}.`)}`);
2235
+ log();
2236
+ suggestCommands(cmd);
2237
+ process.exitCode = 1;
2238
+ });
2239
+
2240
+ if (!process.argv.slice(2).length) {
2241
+ program.outputHelp();
2242
+ process.exit(-1);
2243
+ }
2244
+
2245
+ program.parse(process.argv);
2246
+ var src = src$1;
2247
+
2248
+ module.exports = src;