@tmsfe/tmskit 0.0.5-beta.3 → 0.0.5-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ const SingleEntryPlugin = require('webpack/lib/SingleEntryPlugin');
2
+ const { DEFAULT_WEBPACK_ENTRY, DEFAULT_MODULE_DIR } = require('../../../config/constant');
3
+ const { getEntry } = require('../../utils');
4
+
5
+ class EntryExtraPlugin {
6
+ constructor(options = {}) {
7
+ this.options = options;
8
+ }
9
+
10
+ applyEntry(compiler, entry) {
11
+ const { context } = compiler.options;
12
+
13
+ Object.keys(entry).forEach((key) => {
14
+ new SingleEntryPlugin(context, entry[key], key).apply(compiler);
15
+ });
16
+ }
17
+
18
+ apply(compiler) {
19
+ const { tmsConfig = {}, modules = [] } = this.options;
20
+
21
+ compiler.hooks.watchRun.tap('EntryExtraPlugin', () => {
22
+ const entry = getEntry(DEFAULT_WEBPACK_ENTRY, modules, tmsConfig, DEFAULT_MODULE_DIR);
23
+ this.applyEntry(compiler, entry);
24
+ });
25
+ }
26
+ }
27
+
28
+ module.exports = EntryExtraPlugin;
@@ -0,0 +1,244 @@
1
+ const path = require('path');
2
+ const fs = require('fs');
3
+ const { resolve } = require('../utils/widgets');
4
+ const { buildOutputAppJson } = require('../utils/buildAppJson');
5
+ const { tmsModulesMergeLocalModuleCfg } = require('../utils/tkitUtils');
6
+ const { findAllPackageJson } = require('../utils/npmUtils');
7
+ const { fail } = require('../utils/log');
8
+ const replaceExt = require('replace-ext');
9
+
10
+ const extensions = ['.ts', '.js'];
11
+ function ext(entry, extensions) {
12
+ let newEntry = entry;
13
+ try {
14
+ const stat = fs.lstatSync(newEntry);
15
+ if (stat.isDirectory()) {
16
+ newEntry += (newEntry[newEntry.length - 1] === '/') ? 'index' : '/index';
17
+ }
18
+ } catch (e) {}
19
+
20
+ for (const ext of extensions) {
21
+ const file = replaceExt(newEntry, ext);
22
+ if (fs.existsSync(file)) {
23
+ return {
24
+ file,
25
+ ext,
26
+ };
27
+ }
28
+ }
29
+ return null;
30
+ }
31
+
32
+ // 获取所有的package.json里的依赖包Dir
33
+ function getAlias(modules) {
34
+ const alias = {};
35
+ const allPackages = findAllPackageJson(modules, resolve('./dist'));
36
+ allPackages.forEach((packageFilePath) => {
37
+ const { dependencies } = require(packageFilePath);
38
+ Object.keys(dependencies).forEach((dependence) => {
39
+ alias[dependence] = path.join(path.dirname(packageFilePath), `./miniprogram_npm/${dependence}`);
40
+ });
41
+ });
42
+ return alias;
43
+ }
44
+
45
+
46
+ // 根据用户选择的modules,找到module.config.json的配置信息,找到所有的page
47
+ function getPageEntry(modules, tmsConfig, moduleDir) {
48
+ const entry = {};
49
+ // tms.config.js的modules 合并 module.config.json的配置项
50
+ const newModules = tmsModulesMergeLocalModuleCfg(modules, tmsConfig.appName, moduleDir);
51
+ newModules.forEach(({ path: relativePath, pages, root }) => {
52
+ pages.forEach((page) => {
53
+ const pageJsonPath = `${resolve(relativePath, page)}.json`;
54
+ if (fs.existsSync(pageJsonPath)) {
55
+ const pageJsonContent = JSON.parse(fs.readFileSync(pageJsonPath, 'utf-8'));
56
+ const pageDir = path.dirname(pageJsonPath); // 该页面所在的目录
57
+ const extValue = ext(resolve(relativePath, page), extensions);
58
+ if (!extValue) {
59
+ fail(`当前${page}找不到入口.js或.ts文件`);
60
+ process.exit(1);
61
+ }
62
+ const entryKey = `${root}/${page}${extValue.ext}`;
63
+
64
+ Object.assign(
65
+ entry,
66
+ { [entryKey]: extValue.file },
67
+ getComponentEntry(pageJsonContent, pageDir, path.dirname(entryKey)),
68
+ );
69
+ }
70
+ });
71
+ });
72
+ return entry;
73
+ }
74
+
75
+ // 根据appJson,获取所有的page
76
+ function getEntry(defaultWebpackEntry, modules, tmsConfig, moduleDir) {
77
+ const defaultEntry = {};
78
+ Object.keys(defaultWebpackEntry).forEach((key) => {
79
+ const extValue = ext(defaultWebpackEntry[key], extensions);
80
+ defaultEntry[key + extValue.ext] = extValue.file;
81
+ });
82
+ return {
83
+ ...defaultEntry,
84
+ ...getPageEntry(modules, tmsConfig, moduleDir),
85
+ };
86
+ }
87
+
88
+ // 根据pageJson,filePath,获取页面引入的所有component
89
+ function getComponentEntry(pageJson, pagePath, pageKey) {
90
+ const componentEntry = {};
91
+ function task(json, dir, rootKey) {
92
+ if (!json.usingComponents) {
93
+ return;
94
+ }
95
+
96
+ const componentKeys = Object.keys(json.usingComponents);
97
+
98
+ // 如果存在依赖的组件
99
+ componentKeys.forEach((key) => {
100
+ if (json.usingComponents[key].startsWith('.')) {
101
+ // 拼出组件所在位置的绝对路径
102
+ const comValue = path.join(dir, json.usingComponents[key]);
103
+ const extValue = ext(comValue, extensions);
104
+ const comKey = path.resolve('/', rootKey, json.usingComponents[key]);
105
+ if (!extValue) {
106
+ fail(`当前page: ${pagePath} component: ${comValue}找不到入口.js或.ts文件`);
107
+ process.exit(1);
108
+ }
109
+
110
+ componentEntry[`${comKey.slice(1)}${extValue.ext}`] = extValue.file;
111
+ const comJsonPath = `${comValue}.json`;
112
+ if (fs.existsSync(comJsonPath)) {
113
+ const comJsonContent = JSON.parse(fs.readFileSync(comJsonPath, 'utf-8'));
114
+
115
+ const comDir = path.dirname(comJsonPath); // 该页面所在的目录
116
+ task(comJsonContent, comDir, path.dirname(comKey));
117
+ }
118
+ }
119
+ });
120
+ }
121
+
122
+ task(pageJson, pagePath, pageKey);
123
+
124
+ return componentEntry;
125
+ }
126
+
127
+ // 根据modules处理需要拷贝的模块,copy-webpack-plugin需要的参数
128
+ function getCopyPlugin(defaultCopyConfig, modules, tmsConfig, env) {
129
+ const toPath = tmsConfig.webpack.outputDir;
130
+ function generatorAppJson(tmsConfig, modules) {
131
+ try {
132
+ return buildOutputAppJson(tmsConfig, modules);
133
+ } catch (e) {
134
+ fail(`动态生成app.json出现错误${e} 请检查你的配置项`);
135
+ return {};
136
+ }
137
+ }
138
+
139
+ const patterns = [];
140
+ // 默认的一些配置拷贝文件 package.json、sitemap.json等
141
+ defaultCopyConfig.forEach((item) => {
142
+ if (fs.existsSync(resolve(item))) {
143
+ patterns.push({
144
+ from: resolve(item),
145
+ to: resolve(`./${toPath}/${item}`),
146
+ transform: {
147
+ cache: true,
148
+ },
149
+ });
150
+ }
151
+ });
152
+
153
+ // 拷贝模块的代码
154
+ modules.forEach((item) => {
155
+ patterns.push({
156
+ from: resolve(item.path),
157
+ to: resolve(`./${toPath}/${item.root}`),
158
+ globOptions: {
159
+ ignore: ['**/*.js', '*.js', '**/*.ts', '*.ts'],
160
+ },
161
+ transform: {
162
+ cache: true,
163
+ transformer: env === 'dev'
164
+ ? (content, absoluteFrom) => {
165
+ // 监听module.config.json的修改, 自动生成编译后的app.json
166
+ if (absoluteFrom.indexOf('module.config.json') > -1) {
167
+ generatorAppJson(tmsConfig, modules);
168
+ }
169
+ return content;
170
+ }
171
+ : content => content,
172
+ },
173
+ });
174
+ });
175
+
176
+ if (env === 'dev') {
177
+ // 拷贝app.json时,自动生成编译后的app.json
178
+ const appJsonConfig = ['app.json'];
179
+ appJsonConfig.forEach((item) => {
180
+ patterns.push({
181
+ from: resolve(item),
182
+ to: resolve(`./${toPath}/${item}`),
183
+ transform: {
184
+ cache: true,
185
+ transformer: () => {
186
+ const appJson = generatorAppJson(tmsConfig, modules);
187
+ return JSON.stringify(appJson, null, 2);
188
+ },
189
+ },
190
+ });
191
+ });
192
+ }
193
+
194
+ return patterns;
195
+ }
196
+
197
+ // dev时,给webpack注入相应的事件
198
+ const setupDevWebPackHooks = (context, firstDone) => {
199
+ let tempFirstDone = true;
200
+
201
+ const invalid = () => {
202
+ // eslint-disable-next-line
203
+ context.stats = undefined;
204
+ };
205
+
206
+ const done = (stats) => {
207
+ // eslint-disable-next-line
208
+ context.stats = stats;
209
+
210
+ process.nextTick(() => {
211
+ const { stats } = context;
212
+ if (!stats) return;
213
+
214
+ if (tempFirstDone) {
215
+ tempFirstDone = false;
216
+ firstDone();
217
+ }
218
+ });
219
+ };
220
+ const { compiler } = context;
221
+
222
+ compiler.hooks.watchRun.tap('miniprogram-dev', invalid);
223
+ compiler.hooks.invalid.tap('miniprogram-dev', invalid);
224
+ compiler.hooks.done.tap('miniprogram-dev', done);
225
+ };
226
+
227
+ const stringified = raw => ({
228
+ 'process.env': Object.keys(raw).reduce(
229
+ (env, key) => {
230
+ // eslint-disable-next-line
231
+ env[key] = JSON.stringify(raw[key]);
232
+ return env;
233
+ },
234
+ {},
235
+ ),
236
+ });
237
+
238
+ module.exports = {
239
+ getCopyPlugin,
240
+ setupDevWebPackHooks,
241
+ getEntry,
242
+ stringified,
243
+ getAlias,
244
+ };
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
- }
package/src/gulp/jsDep.js DELETED
@@ -1,150 +0,0 @@
1
- const through = require('through2');
2
- const precinct = require('precinct');
3
- const path = require('path');
4
- const { copyFile, ext, fileInDir } = require('../utils/io');
5
- const { resolve } = require('../utils/widgets');
6
- const fs = require('fs');
7
- const { fail } = require('../utils/log');
8
-
9
- const dfsFindJsDep = function (anaFileOriginFile, anaFileDestFile, extensions) {
10
- const resDep = new Map();
11
- function dfs(anaFileOriginFile, anaFileDestFile, extensions) {
12
- const contents = fs.readFileSync(anaFileOriginFile, 'utf8');
13
- const deps = precinct(contents);
14
- deps.forEach((depItem) => {
15
- if (depItem.startsWith('.')) {
16
- // 被依赖文件的存在的绝对路径
17
- const depOriginPath = path.join(path.dirname(anaFileOriginFile), depItem);
18
- // 被依赖文件加上后缀
19
- const depOriginPathExt = ext(depOriginPath, extensions);
20
-
21
- if (!depOriginPathExt) {
22
- fail(`${anaFileOriginFile}的${depItem}引用路径存找不到文件,请检查引用路径`);
23
- }
24
-
25
- // 被依赖文件是否存在 include的path中 (只处理include的文件)
26
- if (depOriginPathExt) {
27
- const depOriginFile = depOriginPathExt.file;
28
- const depDestPath = resolve(path.dirname(anaFileDestFile), depItem);
29
- const depDestFile = depDestPath.endsWith(depOriginPathExt.ext)
30
- ? depDestPath
31
- : depDestPath + depOriginPathExt.ext;
32
-
33
- if (!resDep.has(depDestFile)) {
34
- resDep.set(depDestFile, {
35
- anaFileOriginFile,
36
- anaFileDestFile,
37
- depDestFile,
38
- depOriginFile,
39
- });
40
- dfs(depOriginFile, depDestFile, extensions);
41
- }
42
- }
43
- }
44
- });
45
- }
46
- dfs(anaFileOriginFile, anaFileDestFile, extensions);
47
-
48
- return resDep;
49
- };
50
-
51
- function handleCopyFile(depDestFile, depOriginFile) {
52
- if (fs.existsSync(depDestFile)) {
53
- const depDestContent = fs.readFileSync(depDestFile, 'utf8');
54
- const depOriginContent = fs.readFileSync(depOriginFile, 'utf8');
55
- if (depDestContent !== depOriginContent) {
56
- console.log(`拷贝${depOriginFile}内容到${depDestFile}`);
57
- copyFile(depOriginFile, depDestFile);
58
- }
59
- } else {
60
- console.log(`拷贝${depOriginFile}内容到${depDestFile}`);
61
- copyFile(depOriginFile, depDestFile);
62
- }
63
- }
64
-
65
- function jsDep(tmsConfig, module, extensions = ['.js', '.ts', '.wxs']) {
66
- const stream = through.obj(function (file, enc, cb) {
67
- // 依赖分析的文件
68
- const anaFileOriginFile = file.history[0];
69
- const anaFileRelativeModule = path.relative(resolve(module.from), anaFileOriginFile);
70
- const anaFileDestFile = resolve(tmsConfig.gulp.outputDir, module.to, anaFileRelativeModule);
71
-
72
- if (file.isBuffer()) {
73
- let contents = String(file.contents);
74
- const deps = precinct(contents);
75
- const copyModules = new Map();
76
-
77
- Object.keys(tmsConfig.gulp.dependencies).forEach((includeName) => {
78
- const includePath = tmsConfig.gulp.dependencies[includeName];
79
- deps.forEach((depItem) => {
80
- if (depItem.indexOf(includeName) > -1) {
81
- // 被依赖文件的存在的绝对路径 (eg: /User/thirdparty/loadsh)
82
- const depOriginPath = path.join(path.dirname(anaFileOriginFile), depItem);
83
- // 被依赖文件加上后缀
84
- const depOriginPathExt = ext(depOriginPath, extensions);
85
-
86
- if (!depOriginPathExt) {
87
- fail(`${anaFileOriginFile}的${depItem}引用路径存找不到文件,请检查引用路径`);
88
- }
89
-
90
- const isFileInDir = fileInDir(includePath, depOriginPathExt.file);
91
- if (!isFileInDir) {
92
- fail(`${depOriginPathExt.file}不在${includePath}不在文件夹内, 请检查应用路径`);
93
- }
94
-
95
- // 被依赖文件是否存在 include的path中 (只处理include的文件)
96
- if (depOriginPathExt && isFileInDir) {
97
- // eslint-disable-next-line
98
- const reg = new RegExp(`^(\.\.\/)+.*\/${includeName}\/(.*)`);
99
- const regRes = depItem.match(reg) || [];
100
- if (regRes[2]) {
101
- const depDestPath = resolve(tmsConfig.gulp.outputDir, module.to, includeName, regRes[2]);
102
- const depDestFile = depDestPath.endsWith(depOriginPathExt.ext)
103
- ? depDestPath
104
- : depDestPath + depOriginPathExt.ext;
105
- // {
106
- // depOriginFile: '/Users/odile/workspace/tms-frontend1/miniprogram/thirdparty/libs/timer.js',
107
- // depDestFile: `/Users/odile/workspace/tms-frontend1/tools/demo1/dist/modules/
108
- // aggredriving/thirdparty/libs/timer.js`,
109
- // beforeDepPath: '../../../../thirdparty/libs/timer',
110
- // afterDepPath: '../../thirdparty/libs/timer'
111
- // }
112
- if (!copyModules.has(depDestFile)) {
113
- copyModules.set(depDestFile, {
114
- depOriginFile: depOriginPathExt.file,
115
- depDestFile,
116
- beforeDepPath: depItem,
117
- afterDepPath: path.relative(path.dirname(anaFileDestFile), depDestPath),
118
- });
119
- }
120
- }
121
- }
122
- }
123
- });
124
- });
125
-
126
- copyModules.forEach(({ depOriginFile, depDestFile, beforeDepPath, afterDepPath }) => {
127
- handleCopyFile(depDestFile, depOriginFile);
128
- contents = contents.replace(beforeDepPath, afterDepPath);
129
-
130
- const defs = dfsFindJsDep(depOriginFile, depDestFile, extensions);
131
- defs.forEach((item) => {
132
- handleCopyFile(item.depDestFile, item.depOriginFile);
133
- });
134
- });
135
-
136
- // eslint-disable-next-line
137
- file.contents = new Buffer(contents);
138
- }
139
-
140
- this.push(file);
141
- cb();
142
- });
143
-
144
- return stream;
145
- }
146
-
147
- module.exports = {
148
- jsDep,
149
- dfsFindJsDep,
150
- };