@tmsfe/tmskit 0.0.5 → 0.0.8

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 (53) hide show
  1. package/README.md +18 -2
  2. package/dist/index.cjs.js +2286 -1258
  3. package/package.json +24 -8
  4. package/src/compile/build.js +5 -0
  5. package/src/compile/compile.js +90 -0
  6. package/src/compile/dev.js +129 -0
  7. package/src/compile/plugins/less.js +116 -0
  8. package/src/compile/plugins/mpCommonDep.js +131 -0
  9. package/src/compile/plugins/mpJsonDep.js +112 -0
  10. package/src/compile/plugins/mpWxmlDep.js +194 -0
  11. package/src/compile/plugins/postcss-font-base64.js +72 -0
  12. package/src/compile/plugins/replaceEnv.js +29 -0
  13. package/src/compile/plugins/utils/pluginError.js +25 -0
  14. package/src/config/constant.js +11 -10
  15. package/src/config/defaultTmsConfig.js +9 -10
  16. package/src/core/buildAppJson.js +166 -0
  17. package/src/{utils → core}/checkDependencies.js +6 -6
  18. package/src/core/cloneModules.js +203 -0
  19. package/src/core/handleError.js +18 -0
  20. package/src/core/isInIt.js +69 -0
  21. package/src/{utils/mpCiUtils.js → core/mpCi.js} +0 -1
  22. package/src/core/npm.js +218 -0
  23. package/src/core/symbolicLink.js +24 -0
  24. package/src/core/tmsMpconfig.js +234 -0
  25. package/src/entry.js +50 -8
  26. package/src/index.js +31 -15
  27. package/src/init.js +2 -7
  28. package/src/scripts/create/index.js +2 -2
  29. package/src/scripts/run/build/index.js +3 -3
  30. package/src/scripts/run/dev/index.js +27 -52
  31. package/src/scripts/run/index.js +70 -36
  32. package/src/scripts/run/init/index.js +40 -42
  33. package/src/scripts/run/install/index.js +21 -29
  34. package/src/utils/findCssImport.js +30 -0
  35. package/src/utils/global.js +19 -33
  36. package/src/utils/io.js +86 -0
  37. package/src/utils/log.js +3 -0
  38. package/src/utils/widgets.js +59 -51
  39. package/CHANGELOG.md +0 -0
  40. package/main.js +0 -3
  41. package/rollup.config.js +0 -179
  42. package/src/utils/buildAppJson.js +0 -144
  43. package/src/utils/cliUtils.js +0 -35
  44. package/src/utils/cloneModules.js +0 -90
  45. package/src/utils/npmUtils.js +0 -126
  46. package/src/utils/tkitUtils.js +0 -84
  47. package/src/webpack/base.js +0 -65
  48. package/src/webpack/build.js +0 -21
  49. package/src/webpack/buildServer.js +0 -34
  50. package/src/webpack/dev.js +0 -31
  51. package/src/webpack/devServer.js +0 -37
  52. package/src/webpack/plugins/entryExtractPlugin/index.js +0 -28
  53. package/src/webpack/utils.js +0 -244
package/package.json CHANGED
@@ -1,11 +1,17 @@
1
1
  {
2
2
  "name": "@tmsfe/tmskit",
3
- "version": "0.0.5",
3
+ "version": "0.0.8",
4
4
  "description": "tmskit",
5
- "main": "main.js",
5
+ "main": "dist/index.cjs",
6
6
  "bin": {
7
7
  "tmskit": "main.js"
8
8
  },
9
+ "files": [
10
+ "src",
11
+ "dist",
12
+ "main.js",
13
+ "package.json"
14
+ ],
9
15
  "scripts": {
10
16
  "dev": "rollup -wc --environment TARGET:tmskit",
11
17
  "build": "rollup -c --environment TARGET:tmskit"
@@ -31,25 +37,35 @@
31
37
  "dependencies": {
32
38
  "async": "^3.2.2",
33
39
  "chalk": "^4.1.0",
34
- "commander": "^6.2.1",
40
+ "commander": "^8.3.0",
35
41
  "copy-webpack-plugin": "^9.1.0",
36
- "download-git-repo": "^3.0.2",
37
42
  "ejs": "^3.1.5",
43
+ "fs-extra": "^10.0.1",
38
44
  "glob-ignore": "^1.0.2",
45
+ "gulp": "^4.0.2",
46
+ "gulp-cache": "^1.1.3",
47
+ "gulp-postcss": "^9.0.1",
48
+ "gulp-px-to-rpx": "^1.0.7",
49
+ "gulp-watch": "^5.0.1",
50
+ "htmlparser2": "^7.2.0",
39
51
  "inquirer": "^7.3.3",
40
52
  "leven": "3.1.0",
41
53
  "lodash": "^4.17.21",
42
54
  "metalsmith": "^2.3.0",
43
55
  "miniprogram-ci": "1.4.13",
56
+ "object-assign": "^4.0.1",
44
57
  "ora": "^5.1.0",
58
+ "plugin-error": "^1.0.0",
59
+ "postcss": "^8.4.6",
60
+ "precinct": "^8.3.1",
45
61
  "replace-ext": "^2.0.0",
46
62
  "shelljs": "^0.8.4",
47
- "ts-loader": "^9.2.6",
48
- "webpack": "^5.64.0",
49
- "webpack-chain": "^6.5.1"
63
+ "strip-comments": "^2.0.1",
64
+ "through2": "^4.0.2",
65
+ "vinyl-sourcemaps-apply": "^0.2.0"
50
66
  },
51
67
  "engines": {
52
- "node": "^12.17.0 || >= 14.0.0"
68
+ "node": "^12.17.0 || >= 14.13.1"
53
69
  },
54
70
  "jest": {
55
71
  "testEnvironment": "jest-environment-node"
@@ -0,0 +1,5 @@
1
+ const dev = require('./dev');
2
+
3
+ module.exports = async (tmsConfig, newModules) => {
4
+ dev(tmsConfig, newModules, false);
5
+ };
@@ -0,0 +1,90 @@
1
+ const { src, dest, lastRun } = require('gulp');
2
+ const px2rpx = require('gulp-px-to-rpx');
3
+ const watch = require('gulp-watch');
4
+ // const cache = require('gulp-cache');
5
+ // const image = require('gulp-image');
6
+ // const replaceEnv = require('./plugins/replaceEnv');
7
+ const { mpCommonDep } = require('./plugins/mpCommonDep');
8
+ const { mpJsonDep } = require('./plugins/mpJsonDep');
9
+ const { mpWxmlDep } = require('./plugins/mpWxmlDep');
10
+ // const postcss = require('gulp-postcss');
11
+ // const base64 = require('./plugins/postcss-font-base64');
12
+ const { fail } = require('../utils/log');
13
+
14
+ const since = task => file => (lastRun(task) > file.stat.ctime ? lastRun(task) : 0);
15
+ module.exports = function (
16
+ tmsConfig,
17
+ {
18
+ glob,
19
+ destPath,
20
+ srcOption,
21
+ module,
22
+ watchOption = { events: ['change', 'add', 'unlink'] },
23
+ isWatch,
24
+ },
25
+ ) {
26
+ Object.keys(glob).forEach((globKey) => {
27
+ const globValue = glob[globKey];
28
+ const task = () => src(globValue, { ...srcOption, since: since(task) });
29
+ let srcPipe = task();
30
+
31
+ if (isWatch) {
32
+ srcPipe = srcPipe.pipe(watch(globValue, watchOption));
33
+ }
34
+
35
+ switch (globKey) {
36
+ case 'js':
37
+ srcPipe
38
+ // .pipe(replaceEnv(/process\.env(\.(\w*))?/g, tmsConfig.envData))
39
+ .pipe(mpCommonDep(tmsConfig, module, ['.js', '.ts', '.wxs', '.json'], isWatch))
40
+ .pipe(dest(destPath))
41
+ .on('error', (err) => {
42
+ fail(`js编译报错${err}`);
43
+ });
44
+ break;
45
+ case 'wxss':
46
+ srcPipe
47
+ .pipe(mpCommonDep(tmsConfig, module, ['.wxss', '.less'], isWatch))
48
+ .on('error', (err) => {
49
+ fail(`mpCommonDep编译报错${err}`);
50
+ })
51
+ // .pipe(postcss([base64()]))
52
+ // .on('error', (err) => {
53
+ // fail(`postcss编译报错${err}`);
54
+ // })
55
+ .pipe(px2rpx({
56
+ designWidth: 375, // 设计稿宽度,默认为750
57
+ precision: 2, // 小数最大精度,默认为6
58
+ }))
59
+ .pipe(dest(destPath));
60
+ break;
61
+ case 'json':
62
+ srcPipe
63
+ .pipe(mpJsonDep(tmsConfig, module, ['.json'], ['.wxml', '.json', '.js', '.ts', '.wxss', '.less'], isWatch))
64
+ .on('error', (err) => {
65
+ fail(`mpJsonDep编译报错${err}`);
66
+ })
67
+ .pipe(dest(destPath));
68
+ break;
69
+ case 'wxml':
70
+ srcPipe
71
+ .pipe(mpWxmlDep(tmsConfig, module, isWatch))
72
+ .pipe(dest(destPath));
73
+ break;
74
+ case 'image':
75
+ srcPipe
76
+ // .pipe(cache(image()))
77
+ // .on('error', (err) => {
78
+ // fail(`image编译报错${err}`);
79
+ // })
80
+ .pipe(dest(destPath));
81
+ break;
82
+ case 'other':
83
+ srcPipe
84
+ .pipe(dest(destPath));
85
+ break;
86
+ default:
87
+ break;
88
+ }
89
+ });
90
+ };
@@ -0,0 +1,129 @@
1
+ const path = require('path');
2
+ const fs = require('fs');
3
+ const watch = require('gulp-watch');
4
+ const { resolve } = require('../utils/widgets');
5
+ const { buildOutputAppJson } = require('../core/buildAppJson');
6
+ const { DEFAULT_COPY_CONFIG } = require('../config/constant');
7
+ const compile = require('./compile');
8
+
9
+ function excludeGlob(glob) {
10
+ const otherArr = new Set();
11
+ otherArr.add('!**/*.{ttf,otf,woff,eot}');
12
+ Object.keys(glob).forEach((globKey) => {
13
+ if (typeof glob[globKey] === 'string') {
14
+ const data = glob[globKey].startsWith('!') ? glob[globKey] : `!${glob[globKey]}`;
15
+ otherArr.add(data);
16
+ } if (Array.isArray(glob[globKey])) {
17
+ glob[globKey].forEach((value) => {
18
+ if (typeof value === 'string') {
19
+ const data = value.startsWith('!') ? value : `!${value}`;
20
+ otherArr.add(data);
21
+ }
22
+ });
23
+ }
24
+ });
25
+ return Array.from(otherArr);
26
+ }
27
+
28
+ function adaptPath(pathDir) {
29
+ let newPath = pathDir;
30
+ newPath = newPath.startsWith('/') ? newPath : resolve(newPath);
31
+ newPath = newPath.endsWith('/') ? newPath.slice(0, newPath.length - 1) : newPath;
32
+ return newPath;
33
+ }
34
+
35
+ module.exports = async (tmsConfig, newModules, isWatch = true) => {
36
+ // 监听app.json
37
+ if (isWatch) {
38
+ watch(resolve('app.json'), { ignoreInitial: false, events: ['add', 'change'] }, () => {
39
+ buildOutputAppJson(tmsConfig, newModules, isWatch);
40
+ });
41
+ } else {
42
+ buildOutputAppJson(tmsConfig, newModules, isWatch);
43
+ }
44
+
45
+ // 监听根目录的文件
46
+ compile(tmsConfig, {
47
+ glob: {
48
+ json: DEFAULT_COPY_CONFIG.map(item => resolve(item)),
49
+ // wxss: ['app.less', 'app.wxss'].map(item => resolve(item)),
50
+ // js: ['app.js', 'app.ts'].map(item => resolve(item)),
51
+ },
52
+ module: { from: '', to: '' },
53
+ destPath: resolve(tmsConfig.outputDir),
54
+ srcOption: { allowEmpty: true },
55
+ isWatch,
56
+ });
57
+
58
+ // 监听模块的文件
59
+ for (let module of newModules) {
60
+ // 处理默认参数
61
+ module = {
62
+ ...{ exclude: [] },
63
+ ...module,
64
+ };
65
+
66
+ if (isWatch) {
67
+ // 监听模块配置文件
68
+ watch(`${resolve(module.path)}/**/module.config.json`, { events: ['change'] }, () => {
69
+ buildOutputAppJson(tmsConfig, newModules, isWatch);
70
+ });
71
+ }
72
+
73
+ const excludes = module.exclude.map(key => `!${resolve(key)}`);
74
+ const modulePath = adaptPath(module.path);
75
+ const glob = {
76
+ js: [`${modulePath}/**/*.{js,ts,wxs}`, ...excludes],
77
+ json: [`${modulePath}/**/*.json`, ...excludes],
78
+ wxss: [`${modulePath}/**/*.{less,wxss}`, ...excludes],
79
+ wxml: [`${modulePath}/**/*.wxml`, ...excludes],
80
+ image: [`${modulePath}/**/*.{png,jpg,jpeg,gif,svg}`, ...excludes],
81
+ };
82
+
83
+ compile(tmsConfig, {
84
+ glob: {
85
+ ...glob,
86
+ other: [`${modulePath}/**/*`, ...excludeGlob(glob)],
87
+ },
88
+ destPath: resolve(tmsConfig.outputDir, module.root),
89
+ module: { from: module.path, to: module.root },
90
+ srcOption: { allowEmpty: true },
91
+ isWatch,
92
+ });
93
+ }
94
+
95
+ // 静态资源目录-拷贝
96
+ if (tmsConfig?.static && tmsConfig?.static.length > 0) {
97
+ for (const item of tmsConfig.static) {
98
+ item.from = adaptPath(item.from);
99
+ item.to = adaptPath(item.to);
100
+
101
+ let glob = {};
102
+ const ext = path.extname(item.from).slice(1);
103
+ if (ext) {
104
+ glob[ext] = [item.from];
105
+ } else {
106
+ glob = {
107
+ js: [`${item.from}/**/*.{js,ts,wxs}`],
108
+ json: [`${item.from}/**/*.json`],
109
+ wxss: [`${item.from}/**/*.{less,wxss}`],
110
+ wxml: [`${item.from}/**/*.wxml`],
111
+ image: [`${item.from}/**/*.{png,jpg,jpeg,gif,svg}`],
112
+ };
113
+ glob.other = [`${item.from}/**/*`, ...excludeGlob(glob)];
114
+ }
115
+
116
+ const from = fs.lstatSync(item.from).isFile() ? path.dirname(item.from) : item.from;
117
+ compile(tmsConfig, {
118
+ glob,
119
+ destPath: item.to,
120
+ module: {
121
+ from,
122
+ to: item.to,
123
+ },
124
+ srcOption: { allowEmpty: true },
125
+ isWatch,
126
+ });
127
+ }
128
+ }
129
+ };
@@ -0,0 +1,116 @@
1
+ /* eslint-disable no-param-reassign */
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const less = require('less');
5
+ const through2 = require('through2');
6
+ const replaceExt = require('replace-ext');
7
+ const assign = require('object-assign');
8
+ const applySourceMap = require('vinyl-sourcemaps-apply');
9
+ const PluginError = require('plugin-error');
10
+ const { fail } = require('../../utils/log');
11
+
12
+ function inlineSources(map) {
13
+ if (map.sourcesContent) {
14
+ return Promise.resolve(map);
15
+ }
16
+
17
+ return Promise.all(map.sources.map(source => new Promise((resolve, reject) => {
18
+ fs.readFile(source, 'utf8', (err, data) => {
19
+ if (err) {
20
+ reject(err);
21
+ } else {
22
+ resolve(data);
23
+ }
24
+ });
25
+ }))).then(
26
+ (contents) => {
27
+ map.sourcesContent = contents;
28
+ return map;
29
+ },
30
+ () => map,
31
+ );
32
+ }
33
+
34
+ function renderLess(str, opts) {
35
+ return new Promise((resolve, reject) => {
36
+ less.render(str, opts, (err, res) => {
37
+ if (err) {
38
+ reject(err);
39
+ } else {
40
+ const obj = {
41
+ result: res.css,
42
+ imports: res.imports,
43
+ };
44
+ if (opts.sourceMap && res.map) {
45
+ obj.sourcemap = JSON.parse(res.map);
46
+ inlineSources(obj.sourcemap).then((map) => {
47
+ obj.sourcemap = map;
48
+ resolve(obj);
49
+ });
50
+ } else {
51
+ resolve(obj);
52
+ }
53
+ }
54
+ });
55
+ });
56
+ }
57
+
58
+ module.exports = function (options) {
59
+ const opts = assign({}, {
60
+ compress: false,
61
+ paths: [],
62
+ isWatch: false,
63
+ }, options);
64
+
65
+ return through2.obj((file, enc, cb) => {
66
+ if (file.isNull()) {
67
+ return cb(null, file);
68
+ }
69
+
70
+ if (file.isStream()) {
71
+ return cb(new PluginError('gulp-less', 'Streaming not supported'));
72
+ }
73
+
74
+ const str = file.contents.toString();
75
+
76
+ // Injects the path of the current file
77
+ opts.filename = file.path;
78
+
79
+ // Bootstrap source maps
80
+ if (file.sourceMap || opts.sourcemap) {
81
+ opts.sourceMap = true;
82
+ }
83
+
84
+ renderLess(str, opts).then((res) => {
85
+ file.contents = Buffer.from(res.result);
86
+ file.path = replaceExt(file.path, '.wxss');
87
+ if (res.sourcemap) {
88
+ res.sourcemap.file = file.relative;
89
+ res.sourcemap.sources = res.sourcemap.sources.map(source => path.relative(file.base, source));
90
+
91
+ applySourceMap(file, res.sourcemap);
92
+ }
93
+ return file;
94
+ })
95
+ .then((file) => {
96
+ console.log(`less编译完成${file.path}`);
97
+ cb(null, file);
98
+ })
99
+ .catch((err) => {
100
+ // Convert the keys so PluginError can read them
101
+ err.lineNumber = err.line;
102
+ err.fileName = err.filename;
103
+
104
+ // Add a better error message
105
+ const message = `${err.message} in file ${err.fileName} line no. ${err.lineNumber}`;
106
+ err.message = message;
107
+ if (opts.isWatch) {
108
+ // watch的时候,报错提示,不退出进程
109
+ fail(err);
110
+ return cb(null, file);
111
+ }
112
+ // 不watch的时候,报错退出进程
113
+ return cb(new PluginError('gulp-less', err));
114
+ });
115
+ });
116
+ };
@@ -0,0 +1,131 @@
1
+ /* eslint-disable no-param-reassign */
2
+ const through = require('through2');
3
+ const precinct = require('precinct');
4
+ const path = require('path');
5
+ const { findCssImports } = require('../../utils/findCssImport');
6
+ const { ext, fileInDir, diffContentCopyFile } = require('../../utils/io');
7
+ const { resolve } = require('../../utils/widgets');
8
+ const fs = require('fs');
9
+ const { pluginError } = require('./utils/pluginError');
10
+
11
+ const cssFilter = ['.less', '.wxss'];
12
+ const dfsFindCommonDep = function (anaFileOriginFile, anaFileDestFile, extensions, isWatch = true) {
13
+ const resDep = new Map();
14
+ function dfs(anaFileOriginFile, anaFileDestFile, extensions) {
15
+ let contents = '';
16
+ try {
17
+ contents = fs.readFileSync(anaFileOriginFile, 'utf8');
18
+ } catch (e) {
19
+ pluginError(e, isWatch);
20
+ }
21
+ const deps = cssFilter.indexOf(path.extname(anaFileOriginFile)) > -1
22
+ ? findCssImports(contents)
23
+ : precinct(contents);
24
+ deps.forEach((depItem) => {
25
+ if (depItem.startsWith('.')) {
26
+ // 被依赖文件的存在的绝对路径
27
+ const depOriginPath = path.join(path.dirname(anaFileOriginFile), depItem);
28
+ // 被依赖文件加上后缀
29
+ const { ext: extAlias, file: depOriginFile, extPath } = ext(depOriginPath, extensions);
30
+
31
+ if (!fs.existsSync(depOriginFile)) {
32
+ pluginError(
33
+ new Error(`${anaFileOriginFile}引用路径${depOriginFile}文件不存在, 请检查应用路径`),
34
+ isWatch,
35
+ );
36
+ return;
37
+ }
38
+
39
+ const depDestPath = resolve(path.dirname(anaFileDestFile), depItem);
40
+ const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
41
+ if (!resDep.has(depDestFile)) {
42
+ resDep.set(depDestFile, {
43
+ anaFileOriginFile,
44
+ anaFileDestFile,
45
+ depDestFile,
46
+ depOriginFile,
47
+ });
48
+ dfs(depOriginFile, depDestFile, extensions);
49
+ }
50
+ }
51
+ });
52
+ }
53
+ dfs(anaFileOriginFile, anaFileDestFile, extensions);
54
+
55
+ return resDep;
56
+ };
57
+
58
+ function mpCommonDep(tmsConfig, module, extensions = [], isWatch = true) {
59
+ const stream = through.obj(function (file, enc, cb) {
60
+ // 依赖分析的文件
61
+ const anaFileOriginFile = file.history[0];
62
+ const anaFileRelativeModule = path.relative(resolve(module.from), anaFileOriginFile);
63
+ const anaFileDestFile = resolve(tmsConfig.outputDir, module.to, anaFileRelativeModule);
64
+
65
+ if (file.isBuffer()) {
66
+ let contents = String(file.contents);
67
+ const deps = cssFilter.indexOf(path.extname(file.path)) > -1 ? findCssImports(contents) : precinct(contents);
68
+
69
+ const copyModules = new Map();
70
+ Object.keys(tmsConfig.dependencies).forEach((includeName) => {
71
+ const includePath = tmsConfig.dependencies[includeName];
72
+ deps.forEach((depItem) => {
73
+ if (depItem.indexOf(includeName) > -1) {
74
+ // 被依赖文件的存在的绝对路径 (eg: /User/thirdparty/loadsh)
75
+ const depOriginPath = path.join(path.dirname(anaFileOriginFile), depItem);
76
+ // 被依赖文件加上后缀
77
+ const { ext: extAlias, file: depOriginFile, extPath } = ext(depOriginPath, extensions);
78
+
79
+ if (!fileInDir(includePath, depOriginFile)) {
80
+ pluginError(
81
+ new Error(`${anaFileOriginFile}引用路径${depOriginFile}不在${includePath}不在文件夹内, 请检查应用路径`),
82
+ isWatch,
83
+ );
84
+ return;
85
+ }
86
+
87
+ // eslint-disable-next-line
88
+ const reg = new RegExp(`^(\./|\.\.\/)+.*\/${includeName}\/(.*)`);
89
+ const regRes = depItem.match(reg) || [];
90
+ if (regRes[2]) {
91
+ const depDestPath = resolve(tmsConfig.outputDir, module.to, includeName, regRes[2]);
92
+ const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
93
+ if (!copyModules.has(depDestFile)) {
94
+ copyModules.set(depDestFile, {
95
+ depOriginFile,
96
+ depDestFile,
97
+ beforeDepPath: depItem,
98
+ afterDepPath: path.relative(path.dirname(anaFileDestFile), depDestPath).replace(/\\/g, '/'),
99
+ });
100
+ }
101
+ }
102
+ }
103
+ });
104
+ });
105
+
106
+ // console.log('mpCommonDep copyModules', copyModules);
107
+ copyModules.forEach(({ depOriginFile, depDestFile, beforeDepPath, afterDepPath }) => {
108
+ diffContentCopyFile(depOriginFile, depDestFile);
109
+ const reg = new RegExp(`['"]${beforeDepPath}["']`, 'g');
110
+ contents = contents.replace(reg, `"${afterDepPath}"`);
111
+
112
+ const defs = dfsFindCommonDep(depOriginFile, depDestFile, extensions, isWatch);
113
+ defs.forEach((item) => {
114
+ diffContentCopyFile(item.depOriginFile, item.depDestFile);
115
+ });
116
+ // console.log('mpCommonDep defs', defs);
117
+ });
118
+
119
+ file.contents = Buffer.from(contents);
120
+ }
121
+ this.push(file);
122
+ cb();
123
+ });
124
+
125
+ return stream;
126
+ }
127
+
128
+ module.exports = {
129
+ mpCommonDep,
130
+ dfsFindCommonDep,
131
+ };
@@ -0,0 +1,112 @@
1
+ /* eslint-disable no-param-reassign */
2
+ const through = require('through2');
3
+ const path = require('path');
4
+ const { ext, fileInDir, diffContentCopyFile } = require('../../utils/io');
5
+ const { resolve } = require('../../utils/widgets');
6
+ const fs = require('fs');
7
+ const { pluginError } = require('./utils/pluginError');
8
+ const { dfsFindCommonDep } = require('./mpCommonDep');
9
+
10
+ function mpJsonDep(
11
+ tmsConfig,
12
+ module,
13
+ extensions = ['.json'],
14
+ filesExt = ['.wxml', '.json', '.js', '.ts', '.wxss', '.less'],
15
+ isWatch,
16
+ ) {
17
+ const stream = through.obj(function (file, enc, cb) {
18
+ // 当前分析的文件的路径
19
+ const anaFileOriginFile = file.history[0];
20
+ const anaFileRelativeModule = path.relative(resolve(module.from), anaFileOriginFile);
21
+ const anaFileDestFile = resolve(tmsConfig.outputDir, module.to, anaFileRelativeModule);
22
+
23
+ if (file.isBuffer()) {
24
+ let contents = String(file.contents);
25
+ const copyModules = new Map();
26
+ try {
27
+ try {
28
+ contents = contents ? JSON.parse(contents) : {};
29
+ } catch (e) {
30
+ throw new Error(`解析${file.path}出现错误,请检查配置信息: ${e}`);
31
+ }
32
+ if (contents.usingComponents) {
33
+ Object.keys(tmsConfig.dependencies).forEach((includeName) => {
34
+ const includePath = tmsConfig.dependencies[includeName];
35
+ Object.keys(contents.usingComponents).forEach((componentKey) => {
36
+ const componentPath = contents.usingComponents[componentKey];
37
+ if (componentPath.indexOf(includeName) > -1) {
38
+ const depOriginPath = path.join(path.dirname(anaFileOriginFile), componentPath);
39
+ // 被依赖文件加上后缀
40
+ const { ext: extAlias, file: depOriginFile, extPath } = ext(depOriginPath, extensions);
41
+
42
+ const isFileInDir = fileInDir(includePath, depOriginFile);
43
+ if (!isFileInDir) {
44
+ pluginError(
45
+ new Error(`${anaFileOriginFile}引用的路径${depOriginFile}不在${includePath}不在文件夹内, 请检查应用路径`),
46
+ isWatch,
47
+ );
48
+ return;
49
+ }
50
+
51
+ // eslint-disable-next-line
52
+ const reg = new RegExp(`^(\./\.\.\/)+.*\/${includeName}\/(.*)`);
53
+ const regRes = componentPath.match(reg) || [];
54
+ if (regRes[2]) {
55
+ const depDestPath = resolve(tmsConfig.outputDir, module.to, includeName, regRes[2]);
56
+ const depDestFile = depDestPath.endsWith(extAlias) ? depDestPath : depDestPath + extPath;
57
+
58
+ if (!copyModules.has(depDestFile)) {
59
+ copyModules.set(depDestFile, {
60
+ depOriginFile,
61
+ depOriginExt: extAlias,
62
+ depDestFile,
63
+ beforeDepPath: componentPath,
64
+ afterDepPath: path.relative(path.dirname(anaFileDestFile), depDestPath).replace(/\\/g, '/'),
65
+ });
66
+ }
67
+ }
68
+ }
69
+ });
70
+ });
71
+ }
72
+ } catch (e) {
73
+ pluginError(e, isWatch);
74
+ }
75
+ // console.log('json copyModules', copyModules);
76
+ copyModules.forEach(({ depOriginFile, depOriginExt, depDestFile, beforeDepPath, afterDepPath }) => {
77
+ // 拷贝当前依赖组件几个部分 wxml、wxss、wxs、json
78
+ filesExt.forEach((extKey) => {
79
+ const originFile = depOriginFile.replace(depOriginExt, extKey);
80
+ const destFile = depDestFile.replace(depOriginExt, extKey);
81
+
82
+ if (fs.existsSync(originFile)) {
83
+ diffContentCopyFile(originFile, destFile);
84
+
85
+ const extensionsFilter = ['.js', '.ts', '.wxss', '.less'];
86
+ if (extensionsFilter.indexOf(extKey) > -1) {
87
+ const defs = dfsFindCommonDep(originFile, destFile, extensionsFilter);
88
+ // console.log('json defs', defs);
89
+ defs.forEach((item) => {
90
+ diffContentCopyFile(item.depOriginFile, item.depDestFile);
91
+ });
92
+ }
93
+ }
94
+ });
95
+ contents = typeof contents === 'object' ? JSON.stringify(contents, null, 2) : contents;
96
+ const reg = new RegExp(`['"]${beforeDepPath}["']`, 'g');
97
+ contents = contents.replace(reg, `"${afterDepPath}"`);
98
+ });
99
+ contents = typeof contents === 'object' ? JSON.stringify(contents, null, 2) : contents;
100
+ file.contents = Buffer.from(contents);
101
+ }
102
+
103
+ this.push(file);
104
+ cb();
105
+ });
106
+
107
+ return stream;
108
+ }
109
+
110
+ module.exports = {
111
+ mpJsonDep,
112
+ };