@umijs/mfsu 4.0.0-rc.12 → 4.0.0-rc.15

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.
package/dist/dep/dep.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -27,11 +18,9 @@ const resolver = enhanced_resolve_1.default.create({
27
18
  exportsFields: ['exports'],
28
19
  conditionNames: ['import', 'module', 'require', 'node'],
29
20
  });
30
- function resolve(context, path) {
31
- return __awaiter(this, void 0, void 0, function* () {
32
- return new Promise((resolve, reject) => {
33
- resolver(context, path, (err, result) => err ? reject(err) : resolve(result));
34
- });
21
+ async function resolve(context, path) {
22
+ return new Promise((resolve, reject) => {
23
+ resolver(context, path, (err, result) => err ? reject(err) : resolve(result));
35
24
  });
36
25
  }
37
26
  class Dep {
@@ -44,49 +33,49 @@ class Dep {
44
33
  this.filePath = `${constants_1.MF_VA_PREFIX}${this.normalizedFile}.js`;
45
34
  this.mfsu = opts.mfsu;
46
35
  }
47
- buildExposeContent() {
48
- return __awaiter(this, void 0, void 0, function* () {
49
- // node natives
50
- // @ts-ignore
51
- const isNodeNatives = !!process.binding('natives')[this.file];
52
- if (isNodeNatives) {
53
- return (0, trimFileContent_1.trimFileContent)(this.mfsu.opts.excludeNodeNatives
54
- ? `
36
+ async buildExposeContent() {
37
+ // node natives
38
+ // @ts-ignore
39
+ const isNodeNatives = !!process.binding('natives')[this.file];
40
+ if (isNodeNatives) {
41
+ return (0, trimFileContent_1.trimFileContent)(this.mfsu.opts.excludeNodeNatives
42
+ ? `
55
43
  const _ = require('${this.file}');
56
44
  module.exports = _;
57
45
  `
58
- : `
46
+ : `
59
47
  import _ from '${this.file}';
60
48
  export default _;
61
49
  export * from '${this.file}';
62
50
  `);
63
- }
64
- // none node natives
65
- const realFile = yield this.getRealFile();
66
- (0, assert_1.default)(realFile, `filePath not found of ${this.file}`);
67
- const content = (0, fs_1.readFileSync)(realFile, 'utf-8');
68
- return yield (0, getExposeFromContent_1.getExposeFromContent)({
69
- content,
70
- filePath: realFile,
71
- dep: this,
72
- });
51
+ }
52
+ // none node natives
53
+ const realFile = await this.getRealFile();
54
+ (0, assert_1.default)(realFile, `filePath not found of ${this.file}`);
55
+ const content = (0, fs_1.readFileSync)(realFile, 'utf-8');
56
+ return await (0, getExposeFromContent_1.getExposeFromContent)({
57
+ content,
58
+ filePath: realFile,
59
+ dep: this,
73
60
  });
74
61
  }
75
- getRealFile() {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- try {
78
- // don't need to handle alias here
79
- // it's already handled by babel plugin
80
- return yield resolve(this.cwd, this.file);
81
- }
82
- catch (e) {
83
- return null;
84
- }
85
- });
62
+ async getRealFile() {
63
+ try {
64
+ // don't need to handle alias here
65
+ // it's already handled by babel plugin
66
+ return await resolve(this.cwd, this.file);
67
+ }
68
+ catch (e) {
69
+ return null;
70
+ }
86
71
  }
87
72
  static buildDeps(opts) {
88
73
  return Object.keys(opts.deps).map((file) => {
89
- return new Dep(Object.assign(Object.assign({}, opts.deps[file]), { cwd: opts.cwd, mfsu: opts.mfsu }));
74
+ return new Dep({
75
+ ...opts.deps[file],
76
+ cwd: opts.cwd,
77
+ mfsu: opts.mfsu,
78
+ });
90
79
  });
91
80
  }
92
81
  static getDepVersion(opts) {
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -16,62 +7,60 @@ exports.getExposeFromContent = void 0;
16
7
  const assert_1 = __importDefault(require("assert"));
17
8
  const path_1 = require("path");
18
9
  const getModuleExports_1 = require("./getModuleExports");
19
- function getExposeFromContent(opts) {
20
- return __awaiter(this, void 0, void 0, function* () {
21
- // Support CSS
22
- if (opts.filePath &&
23
- /\.(css|less|scss|sass|stylus|styl)$/.test(opts.filePath)) {
24
- return `import '${opts.dep.file}';`;
25
- }
26
- // Support Assets Files
27
- if (opts.filePath &&
28
- /\.(json|svg|png|jpe?g|avif|gif|webp|ico|eot|woff|woff2|ttf|txt|text|mdx?)$/.test(opts.filePath)) {
29
- return `
10
+ async function getExposeFromContent(opts) {
11
+ // Support CSS
12
+ if (opts.filePath &&
13
+ /\.(css|less|scss|sass|stylus|styl)$/.test(opts.filePath)) {
14
+ return `import '${opts.dep.file}';`;
15
+ }
16
+ // Support Assets Files
17
+ if (opts.filePath &&
18
+ /\.(json|svg|png|jpe?g|avif|gif|webp|ico|eot|woff|woff2|ttf|txt|text|mdx?)$/.test(opts.filePath)) {
19
+ return `
30
20
  import _ from '${opts.dep.file}';
31
21
  export default _;`.trim();
22
+ }
23
+ (0, assert_1.default)(/(js|jsx|mjs|ts|tsx)$/.test(opts.filePath), `file type not supported for ${(0, path_1.basename)(opts.filePath)}.`);
24
+ const { exports, isCJS } = await (0, getModuleExports_1.getModuleExports)({
25
+ content: opts.content,
26
+ filePath: opts.filePath,
27
+ });
28
+ // cjs
29
+ if (isCJS) {
30
+ return [
31
+ `import _ from '${opts.dep.file}';`,
32
+ `export default _;`,
33
+ `export * from '${opts.dep.file}';`,
34
+ ].join('\n');
35
+ }
36
+ // esm
37
+ else {
38
+ const ret = [];
39
+ let hasExports = false;
40
+ if (exports.includes('default')) {
41
+ ret.push(`import _ from '${opts.dep.file}';`);
42
+ ret.push(`export default _;`);
43
+ hasExports = true;
32
44
  }
33
- (0, assert_1.default)(/(js|jsx|mjs|ts|tsx)$/.test(opts.filePath), `file type not supported for ${(0, path_1.basename)(opts.filePath)}.`);
34
- const { exports, isCJS } = yield (0, getModuleExports_1.getModuleExports)({
35
- content: opts.content,
36
- filePath: opts.filePath,
37
- });
38
- // cjs
39
- if (isCJS) {
40
- return [
41
- `import _ from '${opts.dep.file}';`,
42
- `export default _;`,
43
- `export * from '${opts.dep.file}';`,
44
- ].join('\n');
45
+ if (hasNonDefaultExports(exports) ||
46
+ // export * from 不会有 exports,只会有 imports
47
+ /export\s+\*\s+from/.test(opts.content)) {
48
+ ret.push(`export * from '${opts.dep.file}';`);
49
+ hasExports = true;
45
50
  }
46
- // esm
47
- else {
48
- const ret = [];
49
- let hasExports = false;
50
- if (exports.includes('default')) {
51
+ if (!hasExports) {
52
+ // 只有 __esModule 的全量导出
53
+ if (exports.includes('__esModule')) {
51
54
  ret.push(`import _ from '${opts.dep.file}';`);
52
55
  ret.push(`export default _;`);
53
- hasExports = true;
54
- }
55
- if (hasNonDefaultExports(exports) ||
56
- // export * from 不会有 exports,只会有 imports
57
- /export\s+\*\s+from/.test(opts.content)) {
58
56
  ret.push(`export * from '${opts.dep.file}';`);
59
- hasExports = true;
60
57
  }
61
- if (!hasExports) {
62
- // 只有 __esModule 的全量导出
63
- if (exports.includes('__esModule')) {
64
- ret.push(`import _ from '${opts.dep.file}';`);
65
- ret.push(`export default _;`);
66
- ret.push(`export * from '${opts.dep.file}';`);
67
- }
68
- else {
69
- ret.push(`import '${opts.dep.file}';`);
70
- }
58
+ else {
59
+ ret.push(`import '${opts.dep.file}';`);
71
60
  }
72
- return ret.join('\n');
73
61
  }
74
- });
62
+ return ret.join('\n');
63
+ }
75
64
  }
76
65
  exports.getExposeFromContent = getExposeFromContent;
77
66
  function hasNonDefaultExports(exports) {
@@ -1,45 +1,34 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.getModuleExports = void 0;
13
4
  const es_module_lexer_1 = require("@umijs/bundler-utils/compiled/es-module-lexer");
14
5
  const esbuild_1 = require("@umijs/bundler-utils/compiled/esbuild");
15
6
  const path_1 = require("path");
16
7
  const getCJSExports_1 = require("./getCJSExports");
17
- function getModuleExports({ content, filePath, }) {
18
- return __awaiter(this, void 0, void 0, function* () {
19
- // Support tsx and jsx
20
- if (filePath && /\.(tsx|jsx)$/.test(filePath)) {
21
- content = (yield (0, esbuild_1.transform)(content, {
22
- sourcemap: false,
23
- sourcefile: filePath,
24
- format: 'esm',
25
- target: 'es6',
26
- loader: (0, path_1.extname)(filePath).slice(1),
27
- })).code;
8
+ async function getModuleExports({ content, filePath, }) {
9
+ // Support tsx and jsx
10
+ if (filePath && /\.(tsx|jsx)$/.test(filePath)) {
11
+ content = (await (0, esbuild_1.transform)(content, {
12
+ sourcemap: false,
13
+ sourcefile: filePath,
14
+ format: 'esm',
15
+ target: 'es6',
16
+ loader: (0, path_1.extname)(filePath).slice(1),
17
+ })).code;
18
+ }
19
+ await es_module_lexer_1.init;
20
+ const [imports, exports] = (0, es_module_lexer_1.parse)(content);
21
+ let isCJS = !imports.length && !exports.length;
22
+ let cjsEsmExports = null;
23
+ if (isCJS) {
24
+ cjsEsmExports = (0, getCJSExports_1.getCJSExports)({ content });
25
+ if (cjsEsmExports.includes('__esModule')) {
26
+ isCJS = false;
28
27
  }
29
- yield es_module_lexer_1.init;
30
- const [imports, exports] = (0, es_module_lexer_1.parse)(content);
31
- let isCJS = !imports.length && !exports.length;
32
- let cjsEsmExports = null;
33
- if (isCJS) {
34
- cjsEsmExports = (0, getCJSExports_1.getCJSExports)({ content });
35
- if (cjsEsmExports.includes('__esModule')) {
36
- isCJS = false;
37
- }
38
- }
39
- return {
40
- exports: cjsEsmExports || exports,
41
- isCJS,
42
- };
43
- });
28
+ }
29
+ return {
30
+ exports: cjsEsmExports || exports,
31
+ isCJS,
32
+ };
44
33
  }
45
34
  exports.getModuleExports = getModuleExports;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.DepBuilder = void 0;
13
4
  const bundler_esbuild_1 = require("@umijs/bundler-esbuild");
@@ -24,75 +15,77 @@ class DepBuilder {
24
15
  this.isBuilding = false;
25
16
  this.opts = opts;
26
17
  }
27
- buildWithWebpack(opts) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const config = this.getWebpackConfig({ deps: opts.deps });
30
- return new Promise((resolve, reject) => {
31
- const compiler = this.opts.mfsu.opts.implementor(config);
32
- compiler.run((err, stats) => {
33
- opts.onBuildComplete();
34
- if (err || (stats === null || stats === void 0 ? void 0 : stats.hasErrors())) {
35
- if (err) {
36
- reject(err);
37
- }
38
- if (stats) {
39
- const errorMsg = stats.toString('errors-only');
40
- // console.error(errorMsg);
41
- reject(new Error(errorMsg));
42
- }
18
+ async buildWithWebpack(opts) {
19
+ const config = this.getWebpackConfig({ deps: opts.deps });
20
+ return new Promise((resolve, reject) => {
21
+ const compiler = this.opts.mfsu.opts.implementor(config);
22
+ compiler.run((err, stats) => {
23
+ opts.onBuildComplete();
24
+ if (err || (stats === null || stats === void 0 ? void 0 : stats.hasErrors())) {
25
+ if (err) {
26
+ reject(err);
43
27
  }
44
- else {
45
- resolve(stats);
28
+ if (stats) {
29
+ const errorMsg = stats.toString('errors-only');
30
+ // console.error(errorMsg);
31
+ reject(new Error(errorMsg));
46
32
  }
47
- compiler.close(() => { });
48
- });
33
+ }
34
+ else {
35
+ resolve(stats);
36
+ }
37
+ compiler.close(() => { });
49
38
  });
50
39
  });
51
40
  }
52
41
  // TODO: support watch and rebuild
53
- buildWithESBuild(opts) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const entryContent = (0, getESBuildEntry_1.getESBuildEntry)({ deps: opts.deps });
56
- const ENTRY_FILE = 'esbuild-entry.js';
57
- const tmpDir = this.opts.mfsu.opts.tmpBase;
58
- const entryPath = (0, path_1.join)(tmpDir, ENTRY_FILE);
59
- (0, fs_1.writeFileSync)(entryPath, entryContent, 'utf-8');
60
- const date = new Date().getTime();
61
- yield (0, bundler_esbuild_1.build)({
62
- cwd: this.opts.mfsu.opts.cwd,
63
- entry: {
64
- [`${constants_1.MF_VA_PREFIX}remoteEntry`]: entryPath,
65
- },
66
- config: Object.assign(Object.assign({}, this.opts.mfsu.opts.depBuildConfig), { outputPath: tmpDir, alias: this.opts.mfsu.alias, externals: this.opts.mfsu.externals }),
67
- inlineStyle: true,
68
- });
69
- utils_1.logger.event(`[mfsu] compiled with esbuild successfully in ${+new Date() - date} ms`);
70
- opts.onBuildComplete();
42
+ async buildWithESBuild(opts) {
43
+ const entryContent = (0, getESBuildEntry_1.getESBuildEntry)({ deps: opts.deps });
44
+ const ENTRY_FILE = 'esbuild-entry.js';
45
+ const tmpDir = this.opts.mfsu.opts.tmpBase;
46
+ const entryPath = (0, path_1.join)(tmpDir, ENTRY_FILE);
47
+ (0, fs_1.writeFileSync)(entryPath, entryContent, 'utf-8');
48
+ const date = new Date().getTime();
49
+ await (0, bundler_esbuild_1.build)({
50
+ cwd: this.opts.mfsu.opts.cwd,
51
+ entry: {
52
+ [`${constants_1.MF_VA_PREFIX}remoteEntry`]: entryPath,
53
+ },
54
+ config: {
55
+ ...this.opts.mfsu.opts.depBuildConfig,
56
+ outputPath: tmpDir,
57
+ alias: this.opts.mfsu.alias,
58
+ externals: this.opts.mfsu.externals,
59
+ },
60
+ inlineStyle: true,
71
61
  });
62
+ utils_1.logger.event(`[mfsu] compiled with esbuild successfully in ${+new Date() - date} ms`);
63
+ opts.onBuildComplete();
72
64
  }
73
- build(opts) {
74
- return __awaiter(this, void 0, void 0, function* () {
75
- this.isBuilding = true;
76
- const onBuildComplete = () => {
77
- this.isBuilding = false;
78
- this.completeFns.forEach((fn) => fn());
79
- this.completeFns = [];
65
+ async build(opts) {
66
+ this.isBuilding = true;
67
+ const onBuildComplete = () => {
68
+ this.isBuilding = false;
69
+ this.completeFns.forEach((fn) => fn());
70
+ this.completeFns = [];
71
+ };
72
+ try {
73
+ await this.writeMFFiles({ deps: opts.deps });
74
+ const newOpts = {
75
+ ...opts,
76
+ onBuildComplete,
80
77
  };
81
- try {
82
- yield this.writeMFFiles({ deps: opts.deps });
83
- const newOpts = Object.assign(Object.assign({}, opts), { onBuildComplete });
84
- if (this.opts.mfsu.opts.buildDepWithESBuild) {
85
- yield this.buildWithESBuild(newOpts);
86
- }
87
- else {
88
- yield this.buildWithWebpack(newOpts);
89
- }
78
+ if (this.opts.mfsu.opts.buildDepWithESBuild) {
79
+ await this.buildWithESBuild(newOpts);
90
80
  }
91
- catch (e) {
92
- onBuildComplete();
93
- throw e;
81
+ else {
82
+ await this.buildWithWebpack(newOpts);
94
83
  }
95
- });
84
+ }
85
+ catch (e) {
86
+ onBuildComplete();
87
+ throw e;
88
+ }
96
89
  }
97
90
  onBuildComplete(fn) {
98
91
  if (this.isBuilding) {
@@ -102,18 +95,16 @@ class DepBuilder {
102
95
  fn();
103
96
  }
104
97
  }
105
- writeMFFiles(opts) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- const tmpBase = this.opts.mfsu.opts.tmpBase;
108
- utils_1.fsExtra.mkdirpSync(tmpBase);
109
- // expose files
110
- for (const dep of opts.deps) {
111
- const content = yield dep.buildExposeContent();
112
- (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, dep.filePath), content, 'utf-8');
113
- }
114
- // index file
115
- (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, 'index.js'), '"😛"', 'utf-8');
116
- });
98
+ async writeMFFiles(opts) {
99
+ const tmpBase = this.opts.mfsu.opts.tmpBase;
100
+ utils_1.fsExtra.mkdirpSync(tmpBase);
101
+ // expose files
102
+ for (const dep of opts.deps) {
103
+ const content = await dep.buildExposeContent();
104
+ (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, dep.filePath), content, 'utf-8');
105
+ }
106
+ // index file
107
+ (0, fs_1.writeFileSync)((0, path_1.join)(tmpBase, 'index.js'), '"😛"', 'utf-8');
117
108
  }
118
109
  getWebpackConfig(opts) {
119
110
  var _a, _b;
@@ -1,54 +1,38 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
2
  Object.defineProperty(exports, "__esModule", { value: true });
23
3
  exports.esbuildLoader = void 0;
24
4
  const es_module_lexer_1 = require("@umijs/bundler-utils/compiled/es-module-lexer");
25
5
  const esbuild_1 = require("@umijs/bundler-utils/compiled/esbuild");
26
6
  const path_1 = require("path");
27
- function esbuildTranspiler(source) {
7
+ async function esbuildTranspiler(source) {
28
8
  var _a;
29
- return __awaiter(this, void 0, void 0, function* () {
30
- const done = this.async();
31
- const options = this.getOptions();
32
- const { handler = [], implementation } = options, otherOptions = __rest(options, ["handler", "implementation"]);
33
- const transform = (implementation === null || implementation === void 0 ? void 0 : implementation.transform) || esbuild_1.transform;
34
- const filePath = this.resourcePath;
35
- const ext = (0, path_1.extname)(filePath).slice(1);
36
- const transformOptions = Object.assign(Object.assign({}, otherOptions), { target: (_a = options.target) !== null && _a !== void 0 ? _a : 'es2015', loader: ext !== null && ext !== void 0 ? ext : 'js', sourcemap: this.sourceMap, sourcefile: filePath });
37
- try {
38
- let { code, map } = yield transform(source, transformOptions);
39
- if (handler.length) {
40
- yield es_module_lexer_1.init;
41
- handler.forEach((handle) => {
42
- const [imports, exports] = (0, es_module_lexer_1.parse)(code);
43
- code = handle({ code, imports, exports, filePath });
44
- });
45
- }
46
- done(null, code, map && JSON.parse(map));
47
- }
48
- catch (error) {
49
- done(error);
9
+ const done = this.async();
10
+ const options = this.getOptions();
11
+ const { handler = [], implementation, ...otherOptions } = options;
12
+ const transform = (implementation === null || implementation === void 0 ? void 0 : implementation.transform) || esbuild_1.transform;
13
+ const filePath = this.resourcePath;
14
+ const ext = (0, path_1.extname)(filePath).slice(1);
15
+ const transformOptions = {
16
+ ...otherOptions,
17
+ target: (_a = options.target) !== null && _a !== void 0 ? _a : 'es2015',
18
+ loader: ext !== null && ext !== void 0 ? ext : 'js',
19
+ sourcemap: this.sourceMap,
20
+ sourcefile: filePath,
21
+ };
22
+ try {
23
+ let { code, map } = await transform(source, transformOptions);
24
+ if (handler.length) {
25
+ await es_module_lexer_1.init;
26
+ handler.forEach((handle) => {
27
+ const [imports, exports] = (0, es_module_lexer_1.parse)(code);
28
+ code = handle({ code, imports, exports, filePath });
29
+ });
50
30
  }
51
- });
31
+ done(null, code, map && JSON.parse(map));
32
+ }
33
+ catch (error) {
34
+ done(error);
35
+ }
52
36
  }
53
37
  exports.default = esbuildTranspiler;
54
38
  exports.esbuildLoader = __filename;
package/dist/mfsu.d.ts CHANGED
@@ -29,6 +29,7 @@ export declare class MFSU {
29
29
  buildDepsAgain: boolean;
30
30
  progress: any;
31
31
  onProgress: Function;
32
+ publicPath: string;
32
33
  constructor(opts: IOpts);
33
34
  asyncImport(content: string): string;
34
35
  setWebpackConfig(opts: {
package/dist/mfsu.js CHANGED
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
12
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
4
  };
@@ -38,6 +29,7 @@ class MFSU {
38
29
  this.depConfig = null;
39
30
  this.buildDepsAgain = false;
40
31
  this.progress = { done: false };
32
+ this.publicPath = '/';
41
33
  this.opts = opts;
42
34
  this.opts.mfName = this.opts.mfName || constants_1.DEFAULT_MF_NAME;
43
35
  this.opts.tmpBase =
@@ -46,7 +38,10 @@ class MFSU {
46
38
  this.opts.getCacheDependency = this.opts.getCacheDependency || (() => ({}));
47
39
  this.onProgress = (progress) => {
48
40
  var _a, _b;
49
- this.progress = Object.assign(Object.assign({}, this.progress), progress);
41
+ this.progress = {
42
+ ...this.progress,
43
+ ...progress,
44
+ };
50
45
  (_b = (_a = this.opts).onMFSUProgress) === null || _b === void 0 ? void 0 : _b.call(_a, this.progress);
51
46
  };
52
47
  this.opts.cwd = this.opts.cwd || process.cwd();
@@ -60,84 +55,84 @@ class MFSU {
60
55
  return `await import('${(0, utils_1.winPath)(content)}');`;
61
56
  // return `(async () => await import('${content}'))();`;
62
57
  }
63
- setWebpackConfig(opts) {
58
+ async setWebpackConfig(opts) {
64
59
  var _a;
65
- return __awaiter(this, void 0, void 0, function* () {
66
- const { mfName } = this.opts;
67
- /**
68
- * config
69
- */
70
- // set alias and externals with reference for babel plugin
71
- Object.assign(this.alias, ((_a = opts.config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || {});
72
- this.externals.push(...(0, makeArray_1.makeArray)(opts.config.externals || []));
73
- // entry
74
- const entry = {};
75
- const virtualModules = {};
76
- // ensure entry object type
77
- const entryObject = utils_1.lodash.isString(opts.config.entry)
78
- ? { default: [opts.config.entry] }
79
- : opts.config.entry;
80
- (0, assert_1.default)(utils_1.lodash.isPlainObject(entryObject), `webpack config 'entry' value must be a string or an object.`);
81
- for (const key of Object.keys(entryObject)) {
82
- const virtualPath = `./mfsu-virtual-entry/${key}.js`;
83
- const virtualContent = [];
84
- let index = 1;
85
- let hasDefaultExport = false;
86
- const entryFiles = utils_1.lodash.isArray(entryObject[key])
87
- ? entryObject[key]
88
- : [entryObject[key]];
89
- for (let entry of entryFiles) {
90
- // ensure entry is a file
91
- if ((0, fs_1.statSync)(entry).isDirectory()) {
92
- const realEntry = (0, utils_1.tryPaths)([
93
- (0, path_1.join)(entry, 'index.tsx'),
94
- (0, path_1.join)(entry, 'index.ts'),
95
- ]);
96
- (0, assert_1.default)(realEntry, `entry file not found, please configure the specific entry path. (e.g. 'src/index.tsx')`);
97
- entry = realEntry;
98
- }
99
- const content = (0, fs_1.readFileSync)(entry, 'utf-8');
100
- const [_imports, exports] = yield (0, bundler_utils_1.parseModule)({ content, path: entry });
101
- if (exports.length) {
102
- virtualContent.push(`const k${index} = ${this.asyncImport(entry)}`);
103
- for (const exportName of exports) {
104
- if (exportName === 'default') {
105
- hasDefaultExport = true;
106
- virtualContent.push(`export default k${index}.${exportName}`);
107
- }
108
- else {
109
- virtualContent.push(`export const ${exportName} = k${index}.${exportName}`);
110
- }
60
+ const { mfName } = this.opts;
61
+ /**
62
+ * config
63
+ */
64
+ // set alias and externals with reference for babel plugin
65
+ Object.assign(this.alias, ((_a = opts.config.resolve) === null || _a === void 0 ? void 0 : _a.alias) || {});
66
+ this.externals.push(...(0, makeArray_1.makeArray)(opts.config.externals || []));
67
+ // entry
68
+ const entry = {};
69
+ const virtualModules = {};
70
+ // ensure entry object type
71
+ const entryObject = utils_1.lodash.isString(opts.config.entry)
72
+ ? { default: [opts.config.entry] }
73
+ : opts.config.entry;
74
+ (0, assert_1.default)(utils_1.lodash.isPlainObject(entryObject), `webpack config 'entry' value must be a string or an object.`);
75
+ for (const key of Object.keys(entryObject)) {
76
+ const virtualPath = `./mfsu-virtual-entry/${key}.js`;
77
+ const virtualContent = [];
78
+ let index = 1;
79
+ let hasDefaultExport = false;
80
+ const entryFiles = utils_1.lodash.isArray(entryObject[key])
81
+ ? entryObject[key]
82
+ : [entryObject[key]];
83
+ for (let entry of entryFiles) {
84
+ // ensure entry is a file
85
+ if ((0, fs_1.statSync)(entry).isDirectory()) {
86
+ const realEntry = (0, utils_1.tryPaths)([
87
+ (0, path_1.join)(entry, 'index.tsx'),
88
+ (0, path_1.join)(entry, 'index.ts'),
89
+ ]);
90
+ (0, assert_1.default)(realEntry, `entry file not found, please configure the specific entry path. (e.g. 'src/index.tsx')`);
91
+ entry = realEntry;
92
+ }
93
+ const content = (0, fs_1.readFileSync)(entry, 'utf-8');
94
+ const [_imports, exports] = await (0, bundler_utils_1.parseModule)({ content, path: entry });
95
+ if (exports.length) {
96
+ virtualContent.push(`const k${index} = ${this.asyncImport(entry)}`);
97
+ for (const exportName of exports) {
98
+ if (exportName === 'default') {
99
+ hasDefaultExport = true;
100
+ virtualContent.push(`export default k${index}.${exportName}`);
101
+ }
102
+ else {
103
+ virtualContent.push(`export const ${exportName} = k${index}.${exportName}`);
111
104
  }
112
105
  }
113
- else {
114
- virtualContent.push(this.asyncImport(entry));
115
- }
116
- index += 1;
117
106
  }
118
- if (!hasDefaultExport) {
119
- virtualContent.push(`export default 1;`);
107
+ else {
108
+ virtualContent.push(this.asyncImport(entry));
120
109
  }
121
- virtualModules[virtualPath] = virtualContent.join('\n');
122
- entry[key] = virtualPath;
110
+ index += 1;
123
111
  }
124
- opts.config.entry = entry;
125
- // plugins
126
- opts.config.plugins = opts.config.plugins || [];
127
- // support publicPath auto
128
- let publicPath = opts.config.output.publicPath;
129
- if (publicPath === 'auto') {
130
- publicPath = '/';
112
+ if (!hasDefaultExport) {
113
+ virtualContent.push(`export default 1;`);
131
114
  }
132
- opts.config.plugins.push(...[
133
- new webpack_virtual_modules_1.default(virtualModules),
134
- new this.opts.implementor.container.ModuleFederationPlugin({
135
- name: '__',
136
- remotes: {
137
- [mfName]: this.opts.runtimePublicPath
138
- ? // ref:
139
- // https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes
140
- `
115
+ virtualModules[virtualPath] = virtualContent.join('\n');
116
+ entry[key] = virtualPath;
117
+ }
118
+ opts.config.entry = entry;
119
+ // plugins
120
+ opts.config.plugins = opts.config.plugins || [];
121
+ // support publicPath auto
122
+ let publicPath = opts.config.output.publicPath;
123
+ if (publicPath === 'auto') {
124
+ publicPath = '/';
125
+ }
126
+ this.publicPath = publicPath;
127
+ opts.config.plugins.push(...[
128
+ new webpack_virtual_modules_1.default(virtualModules),
129
+ new this.opts.implementor.container.ModuleFederationPlugin({
130
+ name: '__',
131
+ remotes: {
132
+ [mfName]: this.opts.runtimePublicPath
133
+ ? // ref:
134
+ // https://webpack.js.org/concepts/module-federation/#promise-based-dynamic-remotes
135
+ `
141
136
  promise new Promise(resolve => {
142
137
  const remoteUrlWithVersion = window.publicPath + '${constants_1.REMOTE_FILE_FULL}';
143
138
  const script = document.createElement('script');
@@ -161,77 +156,74 @@ promise new Promise(resolve => {
161
156
  document.head.appendChild(script);
162
157
  })
163
158
  `.trimLeft()
164
- : `${mfName}@${publicPath}${constants_1.REMOTE_FILE_FULL}`,
165
- },
166
- }),
167
- new buildDepPlugin_1.BuildDepPlugin({
168
- onCompileDone: () => {
169
- if (this.depBuilder.isBuilding) {
170
- this.buildDepsAgain = true;
171
- }
172
- else {
173
- this.buildDeps()
174
- .then(() => {
175
- this.onProgress({
176
- done: true,
177
- });
178
- })
179
- .catch((e) => {
180
- utils_1.logger.error(e);
181
- this.onProgress({
182
- done: true,
183
- });
159
+ : `${mfName}@${publicPath}${constants_1.REMOTE_FILE_FULL}`,
160
+ },
161
+ }),
162
+ new buildDepPlugin_1.BuildDepPlugin({
163
+ onCompileDone: () => {
164
+ if (this.depBuilder.isBuilding) {
165
+ this.buildDepsAgain = true;
166
+ }
167
+ else {
168
+ this.buildDeps()
169
+ .then(() => {
170
+ this.onProgress({
171
+ done: true,
184
172
  });
185
- }
186
- },
187
- }),
188
- // new WriteCachePlugin({
189
- // onWriteCache: lodash.debounce(() => {
190
- // this.depInfo.writeCache();
191
- // }, 300),
192
- // }),
193
- ]);
194
- // ensure topLevelAwait enabled
195
- utils_1.lodash.set(opts.config, 'experiments.topLevelAwait', true);
196
- /**
197
- * depConfig
198
- */
199
- this.depConfig = opts.depConfig;
200
- });
173
+ })
174
+ .catch((e) => {
175
+ utils_1.logger.error(e);
176
+ this.onProgress({
177
+ done: true,
178
+ });
179
+ });
180
+ }
181
+ },
182
+ }),
183
+ // new WriteCachePlugin({
184
+ // onWriteCache: lodash.debounce(() => {
185
+ // this.depInfo.writeCache();
186
+ // }, 300),
187
+ // }),
188
+ ]);
189
+ // ensure topLevelAwait enabled
190
+ utils_1.lodash.set(opts.config, 'experiments.topLevelAwait', true);
191
+ /**
192
+ * depConfig
193
+ */
194
+ this.depConfig = opts.depConfig;
201
195
  }
202
- buildDeps() {
203
- return __awaiter(this, void 0, void 0, function* () {
204
- const shouldBuild = this.depInfo.shouldBuild();
205
- if (!shouldBuild) {
206
- utils_1.logger.info('MFSU skip buildDeps');
207
- return;
208
- }
209
- this.depInfo.snapshot();
210
- const deps = dep_1.Dep.buildDeps({
211
- deps: this.depInfo.moduleGraph.depSnapshotModules,
212
- cwd: this.opts.cwd,
213
- mfsu: this,
214
- });
215
- utils_1.logger.info(`MFSU buildDeps since ${shouldBuild}`);
216
- utils_1.logger.debug(deps.map((dep) => dep.file).join(', '));
217
- yield this.depBuilder.build({
218
- deps,
219
- });
220
- // Write cache
221
- this.depInfo.writeCache();
222
- if (this.buildDepsAgain) {
223
- utils_1.logger.info('MFSU buildDepsAgain');
224
- this.buildDepsAgain = false;
225
- this.buildDeps().catch((e) => {
226
- utils_1.logger.error(e);
227
- });
228
- }
196
+ async buildDeps() {
197
+ const shouldBuild = this.depInfo.shouldBuild();
198
+ if (!shouldBuild) {
199
+ utils_1.logger.info('MFSU skip buildDeps');
200
+ return;
201
+ }
202
+ this.depInfo.snapshot();
203
+ const deps = dep_1.Dep.buildDeps({
204
+ deps: this.depInfo.moduleGraph.depSnapshotModules,
205
+ cwd: this.opts.cwd,
206
+ mfsu: this,
229
207
  });
208
+ utils_1.logger.info(`MFSU buildDeps since ${shouldBuild}`);
209
+ utils_1.logger.debug(deps.map((dep) => dep.file).join(', '));
210
+ await this.depBuilder.build({
211
+ deps,
212
+ });
213
+ // Write cache
214
+ this.depInfo.writeCache();
215
+ if (this.buildDepsAgain) {
216
+ utils_1.logger.info('MFSU buildDepsAgain');
217
+ this.buildDepsAgain = false;
218
+ this.buildDeps().catch((e) => {
219
+ utils_1.logger.error(e);
220
+ });
221
+ }
230
222
  }
231
223
  getMiddlewares() {
232
224
  return [
233
225
  (req, res, next) => {
234
- const publicPath = '/';
226
+ const publicPath = this.publicPath;
235
227
  const isMF = req.path.startsWith(`${publicPath}${constants_1.MF_VA_PREFIX}`) ||
236
228
  req.path.startsWith(`${publicPath}${constants_1.MF_DEP_PREFIX}`) ||
237
229
  req.path.startsWith(`${publicPath}${constants_1.MF_STATIC_PREFIX}`);
@@ -151,7 +151,7 @@ class ModuleGraph {
151
151
  this.deleteNode({ mod: importedModulesMap[key], importer: opts.mod });
152
152
  });
153
153
  newDeps.forEach((dep) => {
154
- this.addNode(Object.assign(Object.assign({}, dep), { importer: opts.mod }));
154
+ this.addNode({ ...dep, importer: opts.mod });
155
155
  });
156
156
  }
157
157
  addNode(opts) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/mfsu",
3
- "version": "4.0.0-rc.12",
3
+ "version": "4.0.0-rc.15",
4
4
  "description": "@umijs/mfsu",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/mfsu#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -17,14 +17,14 @@
17
17
  ],
18
18
  "scripts": {
19
19
  "build": "pnpm tsc",
20
- "build:deps": "pnpm esno ../../scripts/bundleDeps.ts",
20
+ "build:deps": "umi-scripts bundleDeps",
21
21
  "dev": "pnpm build -- --watch",
22
- "test": "jest -c ../../jest.turbo.config.ts"
22
+ "test": "umi-scripts jest-turbo"
23
23
  },
24
24
  "dependencies": {
25
- "@umijs/bundler-esbuild": "4.0.0-rc.12",
26
- "@umijs/bundler-utils": "4.0.0-rc.12",
27
- "@umijs/utils": "4.0.0-rc.12",
25
+ "@umijs/bundler-esbuild": "4.0.0-rc.15",
26
+ "@umijs/bundler-utils": "4.0.0-rc.15",
27
+ "@umijs/utils": "4.0.0-rc.15",
28
28
  "enhanced-resolve": "5.9.2"
29
29
  },
30
30
  "devDependencies": {