@tmsfe/tmskit 0.0.5 → 0.0.6

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 (42) hide show
  1. package/README.md +18 -2
  2. package/dist/index.cjs.js +1852 -1050
  3. package/package.json +24 -6
  4. package/src/config/constant.js +5 -2
  5. package/src/config/defaultTmsConfig.js +9 -10
  6. package/src/entry.js +48 -8
  7. package/src/gulp/build.js +5 -0
  8. package/src/gulp/compile.js +87 -0
  9. package/src/gulp/dev.js +102 -0
  10. package/src/gulp/plugins/less.js +116 -0
  11. package/src/gulp/plugins/mpCommonDep.js +131 -0
  12. package/src/gulp/plugins/mpJsonDep.js +108 -0
  13. package/src/gulp/plugins/mpWxmlDep.js +194 -0
  14. package/src/gulp/plugins/postcss-font-base64.js +72 -0
  15. package/src/gulp/plugins/replaceEnv.js +29 -0
  16. package/src/gulp/plugins/utils/pluginError.js +25 -0
  17. package/src/index.js +24 -9
  18. package/src/init.js +0 -5
  19. package/src/scripts/run/build/index.js +5 -4
  20. package/src/scripts/run/dev/index.js +30 -13
  21. package/src/scripts/run/index.js +30 -25
  22. package/src/scripts/run/init/index.js +31 -41
  23. package/src/scripts/run/install/index.js +19 -29
  24. package/src/utils/buildAppJson.js +100 -23
  25. package/src/utils/checkDependencies.js +6 -6
  26. package/src/utils/cloneModules.js +39 -13
  27. package/src/utils/findCssImport.js +30 -0
  28. package/src/utils/handleError.js +16 -0
  29. package/src/utils/io.js +85 -0
  30. package/src/utils/mpCiUtils.js +0 -1
  31. package/src/utils/npmUtils.js +77 -37
  32. package/src/utils/tkitUtils.js +90 -16
  33. package/src/utils/widgets.js +11 -14
  34. package/CHANGELOG.md +0 -0
  35. package/rollup.config.js +0 -179
  36. package/src/webpack/base.js +0 -65
  37. package/src/webpack/build.js +0 -21
  38. package/src/webpack/buildServer.js +0 -34
  39. package/src/webpack/dev.js +0 -31
  40. package/src/webpack/devServer.js +0 -37
  41. package/src/webpack/plugins/entryExtractPlugin/index.js +0 -28
  42. package/src/webpack/utils.js +0 -244
package/src/utils/io.js CHANGED
@@ -1,10 +1,22 @@
1
1
  const fs = require('fs');
2
+ const path = require('path');
2
3
  /**
3
4
  * 判断目录是否为空
4
5
  * @param {string} dirname 目录名
5
6
  * @returns
6
7
  */
7
8
  const isDirEmpty = dirname => fs.promises.readdir(dirname).then(files => files.length === 0);
9
+
10
+ // 判断是否是文件
11
+ const isFile = (pathName) => {
12
+ try {
13
+ const stat = fs.lstatSync(pathName);
14
+ return stat.isFile();
15
+ } catch {
16
+ return false;
17
+ }
18
+ };
19
+
8
20
  /**
9
21
  * 确保目录存在,不存在就创建一个
10
22
  * @param {*} dirname 目录名
@@ -15,7 +27,80 @@ const ensureDirExist = (dirname) => {
15
27
  }
16
28
  };
17
29
 
30
+ // 复制文件
31
+ const copyFile = function (src, dest) {
32
+ if (fs.existsSync(dest)) {
33
+ fs.unlinkSync(dest);
34
+ }
35
+ const dir = path.dirname(dest);
36
+ ensureDirExist(dir);
37
+ fs.copyFileSync(src, dest);
38
+ };
39
+
40
+ // 判断文件内容是否一致,不一致再进行拷贝
41
+ function diffContentCopyFile(originFile, destFile) {
42
+ if (fs.existsSync(destFile)) {
43
+ const depDestContent = fs.readFileSync(destFile, 'utf8');
44
+ const depOriginContent = fs.readFileSync(originFile, 'utf8');
45
+ if (depDestContent !== depOriginContent) {
46
+ console.log(`拷贝${originFile}内容到${destFile}`);
47
+ copyFile(originFile, destFile);
48
+ }
49
+ } else {
50
+ console.log(`拷贝${originFile}内容到${destFile}`);
51
+ copyFile(originFile, destFile);
52
+ }
53
+ }
54
+
55
+ // 添加后缀
56
+ function ext(filePath, extensions) {
57
+ let newFilePath = filePath;
58
+ let extPath = '';
59
+ // try catch需要包裹:用来处理'./lib/timer'没有后缀的情况
60
+ try {
61
+ const stat = fs.lstatSync(newFilePath);
62
+ if (stat.isDirectory()) {
63
+ extPath = newFilePath[newFilePath.length - 1] === '/' ? 'index' : '/index';
64
+ newFilePath += extPath;
65
+ }
66
+ } catch (e) {}
67
+
68
+ for (const ext of extensions) {
69
+ const file = newFilePath.endsWith(ext) ? newFilePath : newFilePath + ext;
70
+ if (fs.existsSync(file)) {
71
+ return {
72
+ ext,
73
+ extPath: extPath + ext,
74
+ file,
75
+ };
76
+ }
77
+ }
78
+ return {
79
+ ext: '',
80
+ extPath,
81
+ file: filePath,
82
+ };
83
+ }
84
+
85
+ // 判断文件是否在某个目录
86
+ const fileInDir = (dir, file) => {
87
+ if (!fs.existsSync(dir) || !fs.existsSync(file)) {
88
+ return false;
89
+ }
90
+ const relativePath = path.relative(dir, file);
91
+ if (relativePath.startsWith('..')) {
92
+ return false;
93
+ }
94
+ return true;
95
+ };
96
+
97
+
18
98
  module.exports = {
19
99
  isDirEmpty,
100
+ copyFile,
101
+ diffContentCopyFile,
20
102
  ensureDirExist,
103
+ ext,
104
+ fileInDir,
105
+ isFile,
21
106
  };
@@ -1,4 +1,3 @@
1
- /* eslint-disable require-jsdoc */
2
1
  const ci = require('miniprogram-ci');
3
2
  const path = require('path');
4
3
 
@@ -2,55 +2,74 @@
2
2
  * 本文件主要负责项目或者分包依赖的npm的安装
3
3
  */
4
4
  const fs = require('fs');
5
+ const fsExtra = require('fs-extra');
6
+ const crypto = require('crypto');
5
7
  const path = require('path');
6
8
  const shell = require('shelljs');
9
+ const glob = require('glob-ignore');
7
10
  const LOG = require('./log');
8
11
 
9
- const dirpath = process.cwd(); // 项目根目录
12
+ const shellJsOption = { async: false, silent: true };
13
+ const dirPath = process.cwd(); // 项目根目录
10
14
 
11
- const getTarNpmFilename = targetDir => `${targetDir.replaceAll('/', '-')}.tar.gz`;
15
+ const install = async (packageJsonPath = '', retry = true, cacheDir) => {
16
+ const obj = {};
17
+ const packageContent = fs.readFileSync(packageJsonPath);
18
+ const packageJson = JSON.parse(packageContent);
19
+ obj.dependencies = packageJson.dependencies || {};
20
+ // obj.devDependencies = packageJson.devDependencies || {};
12
21
 
13
- // 缓存npm
14
- const npmCache = function (targetDir, cacheDir) {
15
- if (!fs.existsSync(cacheDir)) {
16
- fs.mkdirSync(cacheDir);
22
+ // dependencies和devDependencies字段为空,没有需要安装的npm包,直接return
23
+ // if (Object.keys(obj.dependencies).length === 0 && Object.keys(obj.devDependencies).length === 0) {
24
+ if (Object.keys(obj.dependencies).length === 0) {
25
+ return;
17
26
  }
18
- const tarNpmFilename = getTarNpmFilename(targetDir);
19
- const tarNpmFilePath = `${cacheDir}/${tarNpmFilename}`;
20
- if (fs.existsSync(tarNpmFilePath)) {
21
- shell.rm('-rf', tarNpmFilePath);
22
- }
23
- const cmd = `tar -zcvf ${tarNpmFilePath} ./node_modules`;
24
- shell.exec(cmd, { async: true, silent: true });
25
- // tar -zcvf /Users/odile/.tmskit/node_modules.tar.gz ./node_modules
26
- };
27
27
 
28
- // 获取缓存npm包
29
- const getNpmCache = function (targetDir, cacheDir) {
30
- const tarNpmFilename = getTarNpmFilename(targetDir);
31
- const tarNpmFilePath = `${cacheDir}/${tarNpmFilename}`;
32
- if (fs.existsSync(tarNpmFilePath)) {
33
- const cmd = `tar -zxvf ${tarNpmFilePath} -C ./`;
34
- shell.exec(cmd, { async: false, silent: true });
28
+ // 以package.json中dependencies字段stringify后的md5值作为缓存key
29
+ // 任意包名或者版本号的差异,将导致md5后的差异,从而导致缓存失效,重新下载
30
+ // 如此来保证npm缓存的准确性
31
+ const str = JSON.stringify(obj);
32
+ const key = crypto.createHash('md5').update(str)
33
+ .digest('hex');
34
+ const keyPath = path.join(cacheDir, key);
35
+ const tarFile = path.join(keyPath, 'node_modules.tar.gz');
36
+
37
+ // npm缓存路径不存在
38
+ // 或者缓存的包大小小于512byte,认为缓存不合法
39
+ // 清空缓存目录,重新下载npm包缓存
40
+ const missCache = !fsExtra.pathExistsSync(keyPath)
41
+ || !fsExtra.existsSync(tarFile)
42
+ || fsExtra.statSync(tarFile).size < 512;
43
+ if (missCache) {
44
+ console.log(`未命中缓存,下载${packageJsonPath}依赖`);
45
+ fsExtra.emptydirSync(keyPath);
46
+ shell.cp('-f', packageJsonPath, keyPath);
47
+ shell.cd(keyPath);
48
+ try {
49
+ shell.exec('npx yarn --production --registry http://mirrors.tencent.com/npm/', shellJsOption);
50
+ } catch (err) {
51
+ console.log('err', err);
52
+ if (retry) {
53
+ return await install(packageJsonPath, false);
54
+ }
55
+ throw err;
56
+ }
57
+ shell.exec('tar -zcvf ./node_modules.tar.gz ./node_modules', shellJsOption);
58
+ shell.exec('rm -rf ./node_modules', shellJsOption);
35
59
  }
36
- // tar -zxvf /Users/odile/.tmskit/node_modules.tar.gz -C ./
60
+ shell.cp('-Rf', tarFile, `${path.dirname(packageJsonPath)}/`);
61
+ shell.cd(path.dirname(packageJsonPath));
62
+
63
+ shell.exec('tar -xzvf ./node_modules.tar.gz -C ./', shellJsOption);
64
+ shell.exec('rm -rf ./node_modules.tar.gz', shellJsOption);
65
+ return { missCache, key };
37
66
  };
38
67
 
39
68
 
40
69
  // 遍历安装指定目录下所有项目的npm依赖
41
- const npmInstallAll = async (modules, contextDir, cacheDir) => {
70
+ const mpNpmInstallAll = async (modules, contextDir, cacheDir) => {
42
71
  const packageJsonFiles = await findAllPackageJson(modules, contextDir);
43
-
44
- await Promise.all(packageJsonFiles.map(file => new Promise((resolve) => {
45
- const dir = path.dirname(file);
46
- shell.cd(dir);
47
- if (!fs.existsSync(`${dir}/node_modules`)) {
48
- getNpmCache(dir, cacheDir);
49
- }
50
- shell.exec('npx pnpm install --prod --registry http://mirrors.tencent.com/npm/', { silent: false });
51
- resolve();
52
- npmCache(dir, cacheDir);
53
- })));
72
+ await Promise.all(packageJsonFiles.map(file => install(file, true, cacheDir)));
54
73
  };
55
74
 
56
75
  /**
@@ -106,10 +125,14 @@ const findFilesByFilter = (startPath, filter) => {
106
125
  */
107
126
  const findAllPackageJson = (subRoots = [], contextDir) => {
108
127
  const packageJsonName = 'package.json'; // 查找文件名
109
- const cwd = contextDir || dirpath;
128
+ const cwd = contextDir || dirPath;
110
129
  const result = [path.join(cwd, packageJsonName)]; // 默认填充根目录下的package.json
111
130
 
112
131
  subRoots.forEach((subRoot) => {
132
+ if (!subRoot.root) {
133
+ LOG.fail(`请检查${subRoot.name}的module.config.json是否有root字段`);
134
+ process.exit(1);
135
+ }
113
136
  const toppath = path.join(cwd, subRoot.root); // 从该目录开始查找package.json文件
114
137
  const list = findFilesByFilter(toppath, packageJsonName);
115
138
 
@@ -119,8 +142,25 @@ const findAllPackageJson = (subRoots = [], contextDir) => {
119
142
  return result;
120
143
  };
121
144
 
145
+ function cloudNpmInstall(contextDir) {
146
+ return new Promise((resolve, reject) => {
147
+ glob(`${contextDir}/**/package.json`, ['node_modules', 'miniprogram_npm'], (err, files) => {
148
+ if (err) {
149
+ reject(err);
150
+ }
151
+ files.forEach((file) => {
152
+ const dir = path.dirname(file);
153
+ shell.cd(dir);
154
+ shell.exec('npx npm install --production --registry http://mirrors.tencent.com/npm/', { silent: false });
155
+ });
156
+ resolve();
157
+ });
158
+ });
159
+ }
160
+
122
161
 
123
162
  module.exports = {
124
- npmInstallAll,
163
+ cloudNpmInstall,
164
+ mpNpmInstallAll,
125
165
  findAllPackageJson,
126
166
  };
@@ -1,13 +1,14 @@
1
1
  const loadash = require('lodash');
2
2
  const fs = require('fs');
3
- const { TMS_NAME, TMS_CONFIG_FILENAME, MODULE_CONFIG_FILENAME } = require('../config/constant');
3
+ const { TMS_NAME, TMS_CONFIG_FILENAME, MODULE_CONFIG_FILENAME, TMS_PRIVATE_FILENAME } = require('../config/constant');
4
4
  const { resolve, isObject } = require('./widgets');
5
- const { setModuleConfig } = require('./buildAppJson');
5
+ const { setModuleConfig, getValidModules } = require('./buildAppJson');
6
6
  const defaultTmsConfig = require('../config/defaultTmsConfig');
7
7
  const { fail } = require('./log');
8
+ const path = require('path');
8
9
 
9
10
  /**
10
- * 读取tms.config.json
11
+ * 读取tms.config.js
11
12
  * @param env {string} 环境变量
12
13
  */
13
14
  const readTmsConfig = function (env) {
@@ -22,9 +23,45 @@ const readTmsConfig = function (env) {
22
23
  });
23
24
  // 合并默认值
24
25
  loadash.mergeWith(tmsConfig, defaultTmsConfig);
26
+ // modules兼容处理
27
+ tmsConfig.modules = convertModules(tmsConfig.modules);
25
28
  return tmsConfig;
26
29
  };
27
30
 
31
+ // convertModules 处理默认值
32
+ const convertModules = (modules) => {
33
+ const newModules = [];
34
+ modules.forEach((module, index) => {
35
+ const newModule = {};
36
+ if (typeof module === 'string') {
37
+ // 路径字符串
38
+ Object.assign(newModule, {
39
+ name: path.basename(module),
40
+ path: module,
41
+ });
42
+ } else if (typeof module === 'object') {
43
+ Object.assign(newModule, module);
44
+ if (module.name === undefined) {
45
+ newModule.name = path.basename(module.path);
46
+ }
47
+ }
48
+ newModules.push(newModule);
49
+ });
50
+ return newModules;
51
+ };
52
+
53
+ /**
54
+ * 读取tms.private.js
55
+ */
56
+ const readTmsPrivateCf = function () {
57
+ let tmsPrivateCg;
58
+ const tmsPrivatePath = resolve(TMS_PRIVATE_FILENAME);
59
+ if (fs.existsSync(tmsPrivatePath)) {
60
+ tmsPrivateCg = require(tmsPrivatePath);
61
+ }
62
+ return tmsPrivateCg;
63
+ };
64
+
28
65
  /**
29
66
  * 从tms.config.json中检索用户传入的有效modules
30
67
  * @param { object } tmsConfig
@@ -32,7 +69,7 @@ const readTmsConfig = function (env) {
32
69
  * @returns
33
70
  */
34
71
  const checkModules = function (tmsConfig, modules) {
35
- const targetModules = [];
72
+ const targetModules = [];
36
73
  modules.forEach((moduleName) => {
37
74
  const module = tmsConfig.modules.find(module => module.name === moduleName);
38
75
  module && targetModules.push(module);
@@ -51,22 +88,29 @@ const checkModules = function (tmsConfig, modules) {
51
88
  * @param {string} moduleDir
52
89
  * @returns
53
90
  */
54
- const tmsModulesMergeLocalModuleCfg = (modules, appName, moduleDir) => {
91
+ const tmsModulesMergeLocalModuleCfg = (modules, appName) => {
55
92
  const newModules = [];
56
93
  modules.forEach(({ path: relativePath, name: moduleName }, moduleIndex) => {
57
94
  const moduleConfigPath = resolve(relativePath, MODULE_CONFIG_FILENAME);
58
95
  if (fs.existsSync(moduleConfigPath)) {
59
- let moduleConfigContent = fs.readFileSync(moduleConfigPath, 'utf-8');
60
- moduleConfigContent = setModuleConfig(moduleConfigContent, appName, moduleDir);
61
- const moduleContentArr = isObject(moduleConfigContent) ? [moduleConfigContent] : moduleConfigContent;
62
- moduleContentArr.forEach(({ name }, moduleContentArrIndex) => {
63
- if (name === moduleName) {
64
- newModules.push({
65
- ...modules[moduleIndex],
66
- ...moduleContentArr[moduleContentArrIndex],
67
- });
68
- }
69
- });
96
+ try {
97
+ let moduleConfigContent = fs.readFileSync(moduleConfigPath, 'utf-8');
98
+ moduleConfigContent = setModuleConfig(moduleConfigContent, appName);
99
+ const moduleContentArr = isObject(moduleConfigContent) ? [moduleConfigContent] : moduleConfigContent;
100
+ getValidModules(moduleContentArr).forEach(({ name }, moduleContentArrIndex) => {
101
+ if (name === moduleName) {
102
+ newModules.push({
103
+ ...modules[moduleIndex],
104
+ ...moduleContentArr[moduleContentArrIndex],
105
+ });
106
+ }
107
+ });
108
+ } catch (e) {
109
+ fail(`${moduleConfigPath}配置错误: ${e}`);
110
+ newModules.push({
111
+ ...modules[moduleIndex],
112
+ });
113
+ }
70
114
  } else {
71
115
  newModules.push({
72
116
  ...modules[moduleIndex],
@@ -76,9 +120,39 @@ const tmsModulesMergeLocalModuleCfg = (modules, appName, moduleDir) => {
76
120
  return newModules;
77
121
  };
78
122
 
123
+ /**
124
+ * 分包依赖了分包的模块 合并所依赖的modules
125
+ * @param { object } tmsConfig
126
+ * @param {array} modules
127
+ * @param {string} moduleDir
128
+ * @returns
129
+ */
130
+ const subModulesMergeDepModules = (tmsConfig, modules) => {
131
+ const moduleNames = [];
132
+ modules.forEach(({ name: moduleName }) => {
133
+ moduleNames.push(moduleName);
134
+ });
135
+ let mergeModules = modules;
136
+ let isOver = true;
137
+ modules.forEach(({ dependencies: dependencyModules }) => {
138
+ dependencyModules?.forEach((item) => {
139
+ // 如果所有模块的dep都在moduleNames内,则所有依赖都齐了
140
+ // 否则递归处理,根据name找到相关配置加到modules里
141
+ if (moduleNames.indexOf(item) === -1) {
142
+ isOver = false;
143
+ const tmpModules = checkModules(tmsConfig, [...new Set([item])]);
144
+ mergeModules = [...mergeModules, ...tmpModules];
145
+ mergeModules = tmsModulesMergeLocalModuleCfg(mergeModules, tmsConfig.appName);
146
+ }
147
+ });
148
+ });
149
+ return isOver ? mergeModules : subModulesMergeDepModules(tmsConfig, mergeModules);
150
+ };
79
151
 
80
152
  module.exports = {
81
153
  readTmsConfig,
154
+ readTmsPrivateCf,
82
155
  checkModules,
83
156
  tmsModulesMergeLocalModuleCfg,
157
+ subModulesMergeDepModules,
84
158
  };
@@ -7,7 +7,7 @@ const fs = require('fs');
7
7
  const shelljs = require('shelljs');
8
8
  const download = require('download-git-repo');
9
9
  const chalk = require('chalk');
10
- const shelljsOptons = { slient: true };
10
+ const shelljsOptions = { slient: true };
11
11
 
12
12
  // 获取当前目录
13
13
  const cwd = process.cwd();
@@ -96,7 +96,7 @@ function downloadRepo(dest, downloadOptions = { repoUrl: '', gitUrl: '', branch:
96
96
  function downloadRepoForGit(url, dest, branch) {
97
97
  const cwd = process.cwd();
98
98
 
99
- return new Promise((resolve) => {
99
+ return new Promise((resolve, reject) => {
100
100
  // 如果目标目录不存在
101
101
  if (fs.existsSync(dest)) {
102
102
  shelljs.rm('-rf', path.join(dest));
@@ -105,7 +105,10 @@ function downloadRepoForGit(url, dest, branch) {
105
105
  shelljs.mkdir('-p', dest);
106
106
  shelljs.cd(dest);
107
107
 
108
- shelljs.exec(`git clone ${url} ${dest} --branch ${branch} --depth 1`, shelljsOptons);
108
+ const gitCloneRes = shelljs.exec(`git clone ${url} ${dest} --branch ${branch} --depth 1`, shelljsOptions);
109
+ if (gitCloneRes.code !== 0) {
110
+ reject(gitCloneRes.stderr);
111
+ }
109
112
 
110
113
  shelljs.cd(cwd);
111
114
  resolve();
@@ -129,22 +132,16 @@ const cost = start => Date.now() - start;
129
132
  function createTask(task, startText, endText) {
130
133
  return async (...args) => {
131
134
  const start = Date.now();
132
- let result;
133
135
 
134
136
  const spinner = ora(startText);
137
+
135
138
  spinner.start();
139
+ console.log('\n');
136
140
 
137
- try {
138
- result = await task(...args);
139
- } catch (e) {
140
- result = e;
141
- console.log(chalk.red(e));
141
+ const result = await task(...args);
142
142
 
143
- process.exit(-1);
144
- } finally {
145
- endText && spinner.succeed(`${endText}, ${cost(start)}ms`);
146
- spinner.stop();
147
- }
143
+ endText && spinner.succeed(`${endText}, ${cost(start)}ms`);
144
+ spinner.stop();
148
145
 
149
146
  return result;
150
147
  };
package/CHANGELOG.md DELETED
File without changes
package/rollup.config.js DELETED
@@ -1,179 +0,0 @@
1
- import path from 'path';
2
- import ts from 'rollup-plugin-typescript2';
3
- import babel from '@rollup/plugin-babel';
4
- import json from '@rollup/plugin-json';
5
- import replace from 'rollup-plugin-replace';
6
- import nodeResolve from 'rollup-plugin-node-resolve';
7
- import commonjs from '@rollup/plugin-commonjs';
8
-
9
- if (!process.env.TARGET) {
10
- throw new Error('TARGET package must be specified via --environment flag.');
11
- }
12
-
13
- // 指定包地址
14
- const packageDir = path.resolve(__dirname);
15
- // 包名
16
- const name = path.basename(packageDir);
17
- // 环境
18
- const interEnv = process.env.INTER_ENV || 'public';
19
-
20
- // eslint-disable-next-line
21
- const packageJson = require('./package.json');
22
-
23
- const packageOptions = packageJson.buildOptions || {};
24
-
25
- function resolve(name) { // eslint-disable-line
26
- return path.resolve(packageDir, name);
27
- }
28
-
29
- const outputConfig = {
30
- esm: {
31
- dir: resolve('dist'),
32
- entryFileNames: '[name].js',
33
- format: 'es',
34
- },
35
- 'esm-browser': {
36
- dir: resolve('dist'),
37
- entryFileNames: '[name].esm-browser.js',
38
- format: 'es',
39
- },
40
- cjs: {
41
- dir: resolve('dist'),
42
- entryFileNames: '[name].cjs.js',
43
- format: 'cjs',
44
- },
45
- global: {
46
- dir: resolve('dist'),
47
- entryFileNames: '[name].global.js',
48
- format: 'iife',
49
- },
50
- };
51
-
52
- const defaultFormats = ['esm'];
53
- // 打包格式
54
- const packageFormats = packageOptions.formats || defaultFormats;
55
-
56
- const packageConfigs = packageFormats.map(format => createConfig(format, outputConfig[format]));
57
-
58
- export default packageConfigs;
59
-
60
- /**
61
- * format rollup package configuration object
62
- * @param {string} format 文件打包格式
63
- * @param {object} output 输出对象
64
- * @param {array} plugins 插件
65
- * @returns {object} rollup配置对象
66
- */
67
- function createConfig(format, output, plugins = []) {
68
- if (!output) {
69
- // eslint-disable-next-line
70
- console.log(require('chalk').yellow(`invalid format: "${format}"`)); // eslint-disable-line no-console
71
- process.exit(1);
72
- }
73
-
74
- output.sourceMap = true; // eslint-disable-line
75
- output.externalLiveBindings = false; // eslint-disable-line
76
-
77
- // 兼容不同的包的入口文件 -- 后面会统一为index.ts
78
- const entryFile = setEntryFile(name);
79
-
80
- // 定制化cjs的插件和esmodule的插件。
81
- const extralPlugin = setEsPlugin(output.format);
82
-
83
- return {
84
- input: entryFile,
85
- output,
86
- external: [],
87
- plugins: [
88
- json({
89
- namedExports: false,
90
- }),
91
- commonjs({
92
- ignoreDynamicRequires: true,
93
- // include: 'node_modules/**', // Default: undefined
94
- browser: true,
95
- }),
96
- babel({
97
- plugins: ['@babel/plugin-proposal-nullish-coalescing-operator', '@babel/plugin-proposal-optional-chaining'],
98
- // exclude: ['node_modules/**'],
99
- }),
100
- // terser(),
101
- createReplacePlugin(),
102
- ...extralPlugin,
103
- ...plugins,
104
- ],
105
- onwarn: (msg, warn) => {
106
- if (!/Circular/.test(msg)) {
107
- warn(msg);
108
- }
109
- },
110
- treeshake: {
111
- moduleSideEffects: false,
112
- },
113
- };
114
- }
115
-
116
- /**
117
- * 兼容现在的包会存在不同入口的情况。 后面会统一为index.ts
118
- * @param { string } packageName 包名称
119
- * @returns { Object } entryFile
120
- */
121
- function setEntryFile(packageName) {
122
- let entryFile = resolve('src/index.js');
123
-
124
- switch (packageName) {
125
- case 'tms-core':
126
- entryFile = {
127
- index: resolve('src/index'),
128
- request: resolve('src/request'),
129
- cloudService: resolve('src/cloudService'),
130
- };
131
- if (interEnv !== 'public') {
132
- entryFile['index-proxy'] = resolve('src/index-proxy');
133
- }
134
- break;
135
- case 'tms-websdk':
136
- entryFile = resolve('src/index.ts');
137
- break;
138
- default:
139
- entryFile = resolve('src/index.js');
140
- };
141
-
142
- return entryFile;
143
- }
144
-
145
- /**
146
- * 定制化cjs和esmodule的插件
147
- * @param { string } format 打包格式
148
- * @returns { Array<plugin> } 插件数组
149
- */
150
- function setEsPlugin(format) {
151
- const extralPlugins = [];
152
-
153
-
154
- if (format.indexOf('es') > -1) {
155
- extralPlugins.push(ts({
156
- tsconfig: resolve('tsconfig.json'),
157
- }));
158
- };
159
- if (format.indexOf('iife') > -1) {
160
- extralPlugins.push(nodeResolve({ jsnext: true, preferBuiltins: true, browser: true }));
161
- }
162
- return extralPlugins;
163
- }
164
-
165
- /**
166
- * 创建变量替换插件
167
- * @returns {function} 插件函数
168
- */
169
- function createReplacePlugin() {
170
- const replacements = {
171
- tmsCore: interEnv === 'public' ? '@tmsfe/tms-core' : '@tmsfe/tms-core',
172
- INTER_ENV_VB: JSON.stringify(interEnv || 'private'),
173
- };
174
-
175
- return replace({
176
- values: replacements,
177
- preventAssignment: true,
178
- });
179
- }