@umijs/preset-umi 4.0.0-beta.15 → 4.0.0-beta.16

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.
@@ -110,7 +110,7 @@ umi build --clean
110
110
  const { vite } = api.args;
111
111
  const markupArgs = yield (0, getMarkupArgs_1.getMarkupArgs)({ api });
112
112
  // @ts-ignore
113
- const markup = yield (0, server_1.getMarkup)(Object.assign(Object.assign({}, markupArgs), { scripts: ['/umi.js'].concat(markupArgs.scripts), esmScript: !!opts.config.esm || vite, path: '/' }));
113
+ const markup = yield (0, server_1.getMarkup)(Object.assign(Object.assign({}, markupArgs), { styles: ['/umi.css'].concat(markupArgs.styles), scripts: ['/umi.js'].concat(markupArgs.scripts), esmScript: !!opts.config.esm || vite, path: '/' }));
114
114
  (0, fs_1.writeFileSync)((0, path_1.join)(api.paths.absOutputPath, 'index.html'), markup, 'utf-8');
115
115
  utils_1.logger.event('build index.html');
116
116
  // print size
@@ -28,11 +28,11 @@ function createRouteMiddleware(opts) {
28
28
  // add noshim attr for skip importmap shim logic for this modules
29
29
  { content: viteRefreshScript, noshim: '' },
30
30
  { src: '/@vite/client', noshim: '' },
31
- '/.umi/umi.ts',
31
+ opts.api.appData.hasSrcDir ? '/src/.umi/umi.ts' : '/.umi/umi.ts',
32
32
  ];
33
33
  const markupArgs = yield (0, getMarkupArgs_1.getMarkupArgs)(opts);
34
34
  // @ts-ignore
35
- const requestHandler = yield (0, server_1.createRequestHandler)(Object.assign(Object.assign({}, markupArgs), { scripts: (vite ? viteScripts : ['/umi.js']).concat(markupArgs.scripts), esmScript: vite }));
35
+ const requestHandler = yield (0, server_1.createRequestHandler)(Object.assign(Object.assign({}, markupArgs), { styles: ['/umi.css'].concat(markupArgs.styles), scripts: (vite ? viteScripts : ['/umi.js']).concat(markupArgs.scripts), esmScript: vite }));
36
36
  requestHandler(req, res, next);
37
37
  });
38
38
  }
@@ -238,7 +238,12 @@ PORT=8888 umi dev
238
238
  key: 'onDevCompileDone',
239
239
  args: opts,
240
240
  });
241
- }, mfsuWithESBuild: (_a = api.config.mfsu) === null || _a === void 0 ? void 0 : _a.esbuild });
241
+ }, mfsuWithESBuild: (_a = api.config.mfsu) === null || _a === void 0 ? void 0 : _a.esbuild, cache: {
242
+ buildDependencies: [
243
+ api.pkgPath,
244
+ api.service.configManager.mainConfigFile || '',
245
+ ].filter(Boolean),
246
+ } });
242
247
  if (enableVite) {
243
248
  yield bundlerVite.dev(opts);
244
249
  }
@@ -15,6 +15,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.getMarkupArgs = void 0;
16
16
  const cheerio_1 = __importDefault(require("@umijs/utils/compiled/cheerio"));
17
17
  function getMarkupArgs(opts) {
18
+ var _a;
18
19
  return __awaiter(this, void 0, void 0, function* () {
19
20
  const headScripts = yield opts.api.applyPlugins({
20
21
  key: 'addHTMLHeadScripts',
@@ -42,7 +43,7 @@ function getMarkupArgs(opts) {
42
43
  });
43
44
  return {
44
45
  mountElementId: opts.api.config.mountElementId,
45
- base: opts.api.config.base,
46
+ base: ((_a = opts.api.config.history) === null || _a === void 0 ? void 0 : _a.type) === 'browser' ? opts.api.config.base : '/',
46
47
  routes: opts.api.appData.routes,
47
48
  favicon,
48
49
  headScripts,
@@ -16,8 +16,7 @@ function resolveProjectDep(opts) {
16
16
  exports.default = (api) => {
17
17
  const configDefaults = {
18
18
  alias: {
19
- umi: process.env.UMI_DIR,
20
- '@umijs/renderer-react': (0, path_1.dirname)(require.resolve('@umijs/renderer-react/package.json')),
19
+ umi: '@@/exports',
21
20
  react: resolveProjectDep({
22
21
  pkg: api.pkg,
23
22
  cwd: api.cwd,
@@ -36,6 +35,7 @@ exports.default = (api) => {
36
35
  publicPath: '/',
37
36
  mountElementId: 'root',
38
37
  base: '/',
38
+ history: { type: 'browser' },
39
39
  };
40
40
  const bundleSchemas = (0, schema_1.getSchemas)();
41
41
  const extraSchemas = (0, schema_2.getSchemas)();
@@ -5,14 +5,20 @@ const utils_1 = require("@umijs/utils");
5
5
  function getSchemas() {
6
6
  return {
7
7
  base: (Joi) => Joi.string(),
8
- plugins: (Joi) => Joi.array().items(Joi.string()),
9
- publicPath: (Joi) => Joi.string().regex(/\/$/).error(new Error('publicPath must end with /')),
10
8
  favicon: (Joi) => Joi.string(),
11
- headScripts: (Joi) => Joi.array().items(Joi.alternatives(Joi.string())),
12
- scripts: (Joi) => Joi.array().items(Joi.alternatives(Joi.string())),
9
+ headScripts: (Joi) => Joi.array(),
10
+ history: (Joi) => Joi.object({
11
+ type: Joi.string().valid('browser', 'hash', 'memory'),
12
+ }),
13
+ links: (Joi) => Joi.array(),
14
+ metas: (Joi) => Joi.array(),
13
15
  mountElementId: (Joi) => Joi.string(),
14
16
  npmClient: (Joi) => Joi.string().valid(utils_1.NpmClientEnum.pnpm, utils_1.NpmClientEnum.tnpm, utils_1.NpmClientEnum.cnpm, utils_1.NpmClientEnum.yarn, utils_1.NpmClientEnum.npm),
17
+ plugins: (Joi) => Joi.array().items(Joi.string()),
18
+ publicPath: (Joi) => Joi.string().regex(/\/$/).error(new Error('publicPath must end with /')),
15
19
  routes: (Joi) => Joi.array().items(Joi.object()),
20
+ scripts: (Joi) => Joi.array(),
21
+ styles: (Joi) => Joi.array(),
16
22
  };
17
23
  }
18
24
  exports.getSchemas = getSchemas;
@@ -101,6 +101,7 @@ class ESMIService {
101
101
  });
102
102
  // get the build ticket id
103
103
  const ticketId = yield this.build(data);
104
+ utils_1.logger.info(`ticketId: ${ticketId}`);
104
105
  // continue to the next request after 2s
105
106
  const next = () => new Promise((resolve) => setTimeout(() => resolve(deferrer()), 2000));
106
107
  const deferrer = () => {
@@ -0,0 +1,8 @@
1
+ import { Plugin } from '@umijs/bundler-utils/compiled/esbuild';
2
+ import type { DepOptimizationOptions } from 'vite';
3
+ /**
4
+ * transform require call to import
5
+ */
6
+ export default function requireToImportPlugin({ exclude, }: {
7
+ exclude: NonNullable<DepOptimizationOptions['exclude']>;
8
+ }): Plugin;
@@ -0,0 +1,61 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ const lodash_1 = require("@umijs/utils/compiled/lodash");
13
+ /**
14
+ * transform require call to import
15
+ */
16
+ function requireToImportPlugin({ exclude, }) {
17
+ const regSafeExclude = exclude.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
18
+ const requireRegExp = new RegExp(`^(${regSafeExclude.join('|')})$`);
19
+ return {
20
+ name: 'preset-umi:esmi-require-to-import',
21
+ setup(build) {
22
+ // handler require calls for external deps
23
+ build.onResolve({
24
+ filter: requireRegExp,
25
+ }, (args) => __awaiter(this, void 0, void 0, function* () {
26
+ if (args.kind === 'require-call') {
27
+ return {
28
+ path: args.path,
29
+ namespace: 'esmi-require-to-import',
30
+ pluginData: {
31
+ resolveDir: args.resolveDir,
32
+ },
33
+ };
34
+ }
35
+ }));
36
+ // replace load content
37
+ build.onLoad({
38
+ filter: /.*/,
39
+ namespace: 'esmi-require-to-import',
40
+ }, (args) => {
41
+ const { resolveDir } = args.pluginData || {};
42
+ const packageName = args.path;
43
+ const starSpecifier = `${(0, lodash_1.camelCase)(packageName)}Star`;
44
+ const defaultSpecifier = `${(0, lodash_1.camelCase)(packageName)}Default`;
45
+ return {
46
+ resolveDir,
47
+ contents: [
48
+ `import * as ${starSpecifier} from '${packageName}';`,
49
+ '',
50
+ `const ${defaultSpecifier} = ${starSpecifier}.default ? ${starSpecifier}.default : ${starSpecifier};`,
51
+ '',
52
+ `export default ${defaultSpecifier};`,
53
+ `export * from '${packageName}';`,
54
+ '',
55
+ ].join('\n'),
56
+ };
57
+ });
58
+ },
59
+ };
60
+ }
61
+ exports.default = requireToImportPlugin;
@@ -0,0 +1,13 @@
1
+ import { Plugin } from '@umijs/bundler-utils/compiled/esbuild';
2
+ import type { DepOptimizationOptions } from 'vite';
3
+ import type { createResolver } from '../../../libs/scan';
4
+ /**
5
+ * only external top level import, exclude sub-path imports for esmi
6
+ * example:
7
+ * - import from 'antd' will be externalized
8
+ * - import from 'antd/dist/antd.less' will not be externalized
9
+ */
10
+ export default function topLevelExternal({ exclude, resolver, }: {
11
+ exclude: NonNullable<DepOptimizationOptions['exclude']>;
12
+ resolver: ReturnType<typeof createResolver>;
13
+ }): Plugin;
@@ -0,0 +1,37 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ /**
13
+ * only external top level import, exclude sub-path imports for esmi
14
+ * example:
15
+ * - import from 'antd' will be externalized
16
+ * - import from 'antd/dist/antd.less' will not be externalized
17
+ */
18
+ function topLevelExternal({ exclude, resolver, }) {
19
+ const regSafeExclude = exclude.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
20
+ const subImportRegExp = new RegExp(`^(${regSafeExclude.join('|')})/`);
21
+ const extRegExp = /\.((?<!d)\.ts|jsx?|tsx)$/;
22
+ return {
23
+ name: 'preset-umi:esmi-top-level-external',
24
+ setup(build) {
25
+ build.onResolve({
26
+ filter: subImportRegExp,
27
+ }, (args) => __awaiter(this, void 0, void 0, function* () {
28
+ const resolved = yield resolver.resolve(args.resolveDir, args.path);
29
+ // only process javascript-like files
30
+ if (extRegExp.test(resolved)) {
31
+ return { path: resolved };
32
+ }
33
+ }));
34
+ },
35
+ };
36
+ }
37
+ exports.default = topLevelExternal;
@@ -16,8 +16,11 @@ const es_module_lexer_1 = require("@umijs/bundler-utils/compiled/es-module-lexer
16
16
  const magic_string_1 = __importDefault(require("magic-string"));
17
17
  const path_1 = require("path");
18
18
  const scan_1 = require("../../libs/scan");
19
+ const requireToImport_1 = __importDefault(require("./esbuildPlugins/requireToImport"));
20
+ const topLevelExternal_1 = __importDefault(require("./esbuildPlugins/topLevelExternal"));
19
21
  const Service_1 = __importDefault(require("./Service"));
20
22
  let importmap = { imports: {}, scopes: {} };
23
+ let importmatches = {};
21
24
  /**
22
25
  * esmi vite plugin
23
26
  */
@@ -25,13 +28,36 @@ function esmi(opts) {
25
28
  return {
26
29
  name: 'preset-umi:esmi',
27
30
  configResolved(config) {
31
+ var _a, _b;
32
+ var _c, _d;
28
33
  const { include, exclude } = config.optimizeDeps;
34
+ (_a = (_c = config.optimizeDeps).include) !== null && _a !== void 0 ? _a : (_c.include = []);
29
35
  // do not pre-compile deps which will be loaded by importmap (for top-level deps)
30
36
  if (include === null || include === void 0 ? void 0 : include.length) {
31
- config.optimizeDeps.include = include.filter((item) => !importmap.imports[item]);
37
+ config.optimizeDeps.include = include.filter((item) => !importmatches[item] && !importmap.imports[item]);
32
38
  }
33
- // exclude pre-compile deps which within importmap by default (for nested deps)
34
- config.optimizeDeps.exclude = (exclude || []).concat(Object.keys(importmap.imports).filter((item) => exclude === null || exclude === void 0 ? void 0 : exclude.includes(item)));
39
+ // exclude pre-compile deps
40
+ config.optimizeDeps.exclude = [
41
+ ...new Set([
42
+ // deps from user config
43
+ ...(exclude || []),
44
+ // deps from local scan
45
+ ...Object.keys(importmatches),
46
+ // deps from esmi analyze result
47
+ ...Object.keys(importmap.imports),
48
+ ]),
49
+ ];
50
+ // apply esbuild plugins
51
+ (_b = (_d = config.optimizeDeps).esbuildOptions) !== null && _b !== void 0 ? _b : (_d.esbuildOptions = {});
52
+ config.optimizeDeps.esbuildOptions.plugins = [
53
+ // transform require call to import
54
+ (0, requireToImport_1.default)({ exclude: config.optimizeDeps.exclude }),
55
+ // make sure vite only external top-level npm imports, and resolve sub-path npm imports
56
+ (0, topLevelExternal_1.default)({
57
+ exclude: config.optimizeDeps.exclude,
58
+ resolver: opts.resolver,
59
+ }),
60
+ ].concat(config.optimizeDeps.esbuildOptions.plugins || []);
35
61
  },
36
62
  transform(source) {
37
63
  try {
@@ -42,9 +68,17 @@ function esmi(opts) {
42
68
  imports.forEach((item) => {
43
69
  const { n: specifier, s: start, e: end } = item;
44
70
  // replace npm package to CDN url for matched imports
45
- if (specifier && importmap.imports[specifier]) {
46
- s !== null && s !== void 0 ? s : (s = new magic_string_1.default(source));
47
- s.overwrite(start, end, importmap.imports[specifier]);
71
+ if (specifier) {
72
+ const replacement =
73
+ // search from local scan matches first (for alias)
74
+ (importmatches[specifier] &&
75
+ importmap.imports[importmatches[specifier]]) ||
76
+ // search from esmi analyze result
77
+ importmap.imports[specifier];
78
+ if (replacement) {
79
+ s !== null && s !== void 0 ? s : (s = new magic_string_1.default(source));
80
+ s.overwrite(start, end, replacement);
81
+ }
48
82
  }
49
83
  });
50
84
  return (s === null || s === void 0 ? void 0 : s.toString()) || source;
@@ -78,7 +112,11 @@ function generatePkgData(api) {
78
112
  name: 'default',
79
113
  path: 'es/index.js',
80
114
  from: '',
81
- deps: Object.entries(api.appData.deps).map(([name, version]) => ({
115
+ deps: Object.entries(api.appData.deps)
116
+ // only compile entry imports
117
+ .filter(([_, { matches }]) => matches.length)
118
+ // convert to esmi config
119
+ .map(([name, { version }]) => ({
82
120
  name,
83
121
  version,
84
122
  usedMap: {
@@ -110,15 +148,29 @@ exports.default = (api) => {
110
148
  // skip umi by default
111
149
  delete api.appData.deps['umi'];
112
150
  // FIXME: force include react & react-dom
113
- api.appData.deps['react'] = api.appData.react.version;
114
- api.appData.deps['react-dom'] = api.appData.react.version;
151
+ api.appData.deps['react'].version = api.appData.react.version;
152
+ api.appData.deps['react-dom'] = {
153
+ version: api.appData.react.version,
154
+ matches: ['react-dom'],
155
+ subpaths: [],
156
+ };
115
157
  const data = generatePkgData(api);
116
158
  const deps = data.pkgInfo.exports.reduce((r, exp) => r.concat(exp.deps.map((dep) => dep.name)), []);
117
159
  const hasNewDep = deps.some((i) => !importmap.imports[i]);
118
160
  // update importmap from esm if there has new import
119
161
  if (hasNewDep) {
120
- // TODO: add local cache and restore
121
162
  importmap = (_a = (yield service.getImportmap(data))) === null || _a === void 0 ? void 0 : _a.importMap;
163
+ // update matches map to dep name
164
+ importmatches = Object.keys(api.appData.deps).reduce((r, dep) => {
165
+ // filter subpath imports
166
+ if (!api.appData.deps[dep].subpaths.length) {
167
+ // map all matches to dep name
168
+ api.appData.deps[dep].matches.forEach((m) => {
169
+ r[m] = dep;
170
+ });
171
+ }
172
+ return r;
173
+ }, {});
122
174
  // because we will replaced package name to CDN url in vite plugin
123
175
  // so we must append scope rules for the CDN url like the import specifier
124
176
  // example:
@@ -194,6 +246,7 @@ exports.default = (api) => {
194
246
  yield refreshImportMap();
195
247
  // TODO: refresh page when importmap changed
196
248
  }),
249
+ resolver,
197
250
  }));
198
251
  return memo;
199
252
  });
@@ -6,4 +6,8 @@ export interface IMock {
6
6
  }
7
7
  export declare function getMockData(opts: {
8
8
  cwd: string;
9
+ mockConfig: {
10
+ exclude?: string[];
11
+ include?: string[];
12
+ };
9
13
  }): Record<string, IMock>;
@@ -13,12 +13,16 @@ function getMockData(opts) {
13
13
  implementor: esbuild_1.default,
14
14
  });
15
15
  utils_1.register.clearFiles();
16
- const ret = utils_1.glob
17
- .sync(constants_1.MOCK_FILE_GLOB, { cwd: opts.cwd })
16
+ const ret = [constants_1.MOCK_FILE_GLOB, ...(opts.mockConfig.include || [])]
17
+ .reduce((memo, pattern) => {
18
+ memo.push(...utils_1.glob.sync(pattern, { cwd: opts.cwd, ignore: ['**/*.d.ts'] }));
19
+ return memo;
20
+ }, [])
18
21
  .reduce((memo, file) => {
19
22
  const mockFile = `${opts.cwd}/${file}`;
20
23
  const m = require(mockFile);
21
- const obj = m.default;
24
+ // Cannot convert undefined or null to object
25
+ const obj = (m === null || m === void 0 ? void 0 : m.default) || {};
22
26
  for (const key of Object.keys(obj)) {
23
27
  const mock = getMock({ key, obj });
24
28
  mock.file = mockFile;
@@ -28,7 +32,7 @@ function getMockData(opts) {
28
32
  utils_1.lodash.isPlainObject(mock.handler) ||
29
33
  typeof mock.handler === 'function', `Mock handler must be function or array or object, but got ${typeof mock.handler} for ${mock.method} in ${mock.file}`);
30
34
  if (memo[id]) {
31
- throw new Error(`${id} is duplicated in ${mockFile} and ${memo[id].file}`);
35
+ utils_1.logger.warn(`${id} is duplicated in ${mockFile} and ${memo[id].file}`);
32
36
  }
33
37
  memo[id] = mock;
34
38
  }
@@ -47,7 +51,7 @@ function getMock(opts) {
47
51
  return { method, path, handler };
48
52
  }
49
53
  function parseKey(key) {
50
- const spliced = key.split(' ');
54
+ const spliced = key.split(/\s+/);
51
55
  const len = spliced.length;
52
56
  if (len === 1) {
53
57
  return { method: constants_1.DEFAULT_METHOD, path: key };
@@ -56,6 +60,7 @@ function parseKey(key) {
56
60
  const [method, path] = spliced;
57
61
  const upperCaseMethod = method.toUpperCase();
58
62
  (0, assert_1.default)(constants_1.VALID_METHODS.includes(upperCaseMethod), `method ${method} is not supported`);
63
+ (0, assert_1.default)(path, `${key}, path is undefined`);
59
64
  return { method: upperCaseMethod, path };
60
65
  }
61
66
  }
@@ -21,6 +21,7 @@ function default_1(api) {
21
21
  exclude: Joi.array()
22
22
  .items(Joi.string())
23
23
  .description('exclude files not parse mock'),
24
+ include: Joi.array().items(Joi.string()),
24
25
  });
25
26
  },
26
27
  },
@@ -37,12 +38,18 @@ function default_1(api) {
37
38
  path: `${api.cwd}/mock`,
38
39
  addToUnWatches: true,
39
40
  onChange: () => {
40
- context.mockData = (0, getMockData_1.getMockData)({ cwd: api.cwd });
41
+ context.mockData = (0, getMockData_1.getMockData)({
42
+ cwd: api.cwd,
43
+ mockConfig: api.config.mock || {},
44
+ });
41
45
  },
42
46
  });
43
47
  });
44
48
  api.addBeforeMiddlewares(() => __awaiter(this, void 0, void 0, function* () {
45
- context.mockData = (0, getMockData_1.getMockData)({ cwd: api.cwd });
49
+ context.mockData = (0, getMockData_1.getMockData)({
50
+ cwd: api.cwd,
51
+ mockConfig: api.config.mock || {},
52
+ });
46
53
  return [
47
54
  (0, createMockMiddleware_1.createMockMiddleware)({
48
55
  context,
@@ -1,14 +1,44 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path_1 = require("path");
3
4
  exports.default = (api) => {
4
- api.addPolyfillImports(() => {
5
+ api.describe({
6
+ key: 'polyfill',
7
+ config: {
8
+ schema(Joi) {
9
+ return Joi.object().keys({
10
+ imports: Joi.array().items(Joi.string()).required().unique(),
11
+ });
12
+ },
13
+ },
14
+ enableBy: () => {
15
+ return process.env.BABEL_POLYFILL !== 'none';
16
+ },
17
+ });
18
+ api.onGenerateFiles(() => {
5
19
  var _a;
6
- return api.config.publicPath === 'auto' && ((_a = api.config.targets) === null || _a === void 0 ? void 0 : _a.ie)
7
- ? [
8
- {
9
- source: require.resolve('current-script-polyfill'),
10
- },
11
- ]
12
- : [];
20
+ api.writeTmpFile({
21
+ path: 'core/polyfill.ts',
22
+ noPluginDir: true,
23
+ tpl: `
24
+ {{#imports}}
25
+ import '{{{ . }}}';
26
+ {{/imports}}
27
+ {{^imports}}
28
+ import 'core-js';
29
+ {{/imports}}
30
+ import 'regenerator-runtime/runtime';
31
+ export {};
32
+ `,
33
+ context: {
34
+ imports: ((_a = api.config.polyfill) === null || _a === void 0 ? void 0 : _a.imports) || [],
35
+ },
36
+ });
37
+ });
38
+ api.addPolyfillImports(() => [{ source: `./core/polyfill` }]);
39
+ api.modifyConfig((memo) => {
40
+ memo.alias['core-js'] = (0, path_1.dirname)(require.resolve('core-js/package'));
41
+ memo.alias['regenerator-runtime'] = (0, path_1.dirname)(require.resolve('regenerator-runtime/package'));
42
+ return memo;
13
43
  });
14
44
  };
@@ -0,0 +1,3 @@
1
+ import { IApi } from '../../types';
2
+ declare const _default: (api: IApi) => void;
3
+ export default _default;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = (api) => {
4
+ api.addPolyfillImports(() => {
5
+ var _a;
6
+ return api.config.publicPath === 'auto' && ((_a = api.config.targets) === null || _a === void 0 ? void 0 : _a.ie)
7
+ ? [
8
+ {
9
+ source: require.resolve('current-script-polyfill'),
10
+ },
11
+ ]
12
+ : [];
13
+ });
14
+ };
@@ -49,6 +49,7 @@ function getRoutes(opts) {
49
49
  parentId: undefined,
50
50
  },
51
51
  routes,
52
+ test: layout.test,
52
53
  });
53
54
  }
54
55
  routes = yield opts.api.applyPlugins({
@@ -64,8 +65,9 @@ function getRouteComponents(opts) {
64
65
  const imports = Object.keys(opts.routes)
65
66
  .map((key) => {
66
67
  const route = opts.routes[key];
67
- if (!route.file)
68
- return `// ${key}: no file to import`;
68
+ if (!route.file) {
69
+ return `'${key}': () => import('./EmptyRoute'),`;
70
+ }
69
71
  // e.g.
70
72
  // component: () => <h1>foo</h1>
71
73
  // component: (() => () => <h1>foo</h1>)()
@@ -9,6 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ const bundler_utils_1 = require("@umijs/bundler-utils");
12
13
  const utils_1 = require("@umijs/utils");
13
14
  const fs_1 = require("fs");
14
15
  const path_1 = require("path");
@@ -25,6 +26,10 @@ exports.default = (api) => {
25
26
  },
26
27
  });
27
28
  api.onGenerateFiles((opts) => __awaiter(void 0, void 0, void 0, function* () {
29
+ const rendererPath = yield api.applyPlugins({
30
+ key: 'modifyRendererPath',
31
+ initialValue: (0, path_1.dirname)(require.resolve('@umijs/renderer-react/package.json')),
32
+ });
28
33
  // umi.ts
29
34
  api.writeTmpFile({
30
35
  noPluginDir: true,
@@ -32,10 +37,7 @@ exports.default = (api) => {
32
37
  tplPath: (0, path_1.join)(constants_1.TEMPLATES_DIR, 'umi.tpl'),
33
38
  context: {
34
39
  mountElementId: api.config.mountElementId,
35
- rendererPath: yield api.applyPlugins({
36
- key: 'modifyRendererPath',
37
- initialValue: '@umijs/renderer-react',
38
- }),
40
+ rendererPath,
39
41
  entryCode: (yield api.applyPlugins({
40
42
  key: 'addEntryCode',
41
43
  initialValue: [],
@@ -57,8 +59,20 @@ exports.default = (api) => {
57
59
  initialValue: [],
58
60
  })).join('\n'),
59
61
  basename: api.config.base,
62
+ historyType: api.config.history.type,
60
63
  },
61
64
  });
65
+ // EmptyRoutes.tsx
66
+ api.writeTmpFile({
67
+ noPluginDir: true,
68
+ path: 'core/EmptyRoute.tsx',
69
+ content: `
70
+ import { Outlet } from 'umi';
71
+ export default function EmptyRoute() {
72
+ return <Outlet />;
73
+ }
74
+ `,
75
+ });
62
76
  // route.ts
63
77
  let routes;
64
78
  if (opts.isFirstTime) {
@@ -126,5 +140,73 @@ exports.default = (api) => {
126
140
  validKeys: validKeys,
127
141
  },
128
142
  });
143
+ // history.ts
144
+ api.writeTmpFile({
145
+ noPluginDir: true,
146
+ path: 'core/history.ts',
147
+ tplPath: (0, path_1.join)(constants_1.TEMPLATES_DIR, 'history.tpl'),
148
+ context: {
149
+ rendererPath,
150
+ },
151
+ });
129
152
  }));
153
+ function getExports(opts) {
154
+ return __awaiter(this, void 0, void 0, function* () {
155
+ const content = (0, fs_1.readFileSync)(opts.path, 'utf-8');
156
+ const [_, exports] = yield (0, bundler_utils_1.parseModule)({ content, path: opts.path });
157
+ return exports || [];
158
+ });
159
+ }
160
+ // Generate @@/exports.ts
161
+ api.register({
162
+ key: 'onGenerateFiles',
163
+ fn: () => __awaiter(void 0, void 0, void 0, function* () {
164
+ const exports = [];
165
+ // @umijs/renderer-react
166
+ exports.push('// @umijs/renderer-react');
167
+ const rendererReactPath = (0, path_1.dirname)(require.resolve('@umijs/renderer-react/package.json'));
168
+ exports.push(`export { ${(yield getExports({
169
+ path: (0, path_1.join)(rendererReactPath, 'dist/index.js'),
170
+ })).join(', ')} } from '${rendererReactPath}';`);
171
+ // umi/client/client/plugin
172
+ exports.push('// umi/client/client/plugin');
173
+ const umiDir = process.env.UMI_DIR;
174
+ const umiPluginPath = (0, path_1.join)(umiDir, 'client/client/plugin.js');
175
+ exports.push(`export { ${(yield getExports({
176
+ path: umiPluginPath,
177
+ })).join(', ')} } from '${umiPluginPath}';`);
178
+ // @@/core/history.ts
179
+ exports.push(`export { history, createHistory } from './core/history';`);
180
+ // plugins
181
+ exports.push('// plugins');
182
+ const plugins = (0, fs_1.readdirSync)(api.paths.absTmpPath).filter((file) => {
183
+ if (file.startsWith('plugin-') &&
184
+ ((0, fs_1.existsSync)((0, path_1.join)(api.paths.absTmpPath, file, 'index.ts')) ||
185
+ (0, fs_1.existsSync)((0, path_1.join)(api.paths.absTmpPath, file, 'index.tsx')))) {
186
+ return true;
187
+ }
188
+ });
189
+ for (const plugin of plugins) {
190
+ let file;
191
+ if ((0, fs_1.existsSync)((0, path_1.join)(api.paths.absTmpPath, plugin, 'index.ts'))) {
192
+ file = (0, path_1.join)(api.paths.absTmpPath, plugin, 'index.ts');
193
+ }
194
+ if ((0, fs_1.existsSync)((0, path_1.join)(api.paths.absTmpPath, plugin, 'index.tsx'))) {
195
+ file = (0, path_1.join)(api.paths.absTmpPath, plugin, 'index.tsx');
196
+ }
197
+ const pluginExports = yield getExports({
198
+ path: file,
199
+ });
200
+ if (pluginExports.length) {
201
+ exports.push(`export { ${pluginExports.join(', ')} } from '${(0, path_1.join)(api.paths.absTmpPath, plugin)}';`);
202
+ }
203
+ }
204
+ api.writeTmpFile({
205
+ noPluginDir: true,
206
+ path: 'exports.ts',
207
+ content: exports.join('\n'),
208
+ });
209
+ }),
210
+ stage: Infinity,
211
+ });
130
212
  };
package/dist/index.js CHANGED
@@ -13,6 +13,7 @@ exports.default = () => {
13
13
  require.resolve('./features/favicon/favicon'),
14
14
  require.resolve('./features/mock/mock'),
15
15
  require.resolve('./features/polyfill/polyfill'),
16
+ require.resolve('./features/polyfill/publicPathPolyfill'),
16
17
  require.resolve('./features/tmpFiles/tmpFiles'),
17
18
  require.resolve('./features/transform/transform'),
18
19
  require.resolve('./features/lowImport/lowImport'),
@@ -24,5 +24,9 @@ export declare function scan(opts: {
24
24
  entry: string;
25
25
  externals: any;
26
26
  resolver: any;
27
- }): Promise<Record<string, string>>;
27
+ }): Promise<Record<string, {
28
+ version: string;
29
+ matches: string[];
30
+ subpaths: string[];
31
+ }>>;
28
32
  export {};
package/dist/libs/scan.js CHANGED
@@ -79,6 +79,7 @@ function createResolver(opts) {
79
79
  }
80
80
  exports.createResolver = createResolver;
81
81
  function scan(opts) {
82
+ var _a, _b;
82
83
  return __awaiter(this, void 0, void 0, function* () {
83
84
  const cache = new Map();
84
85
  const queueDeps = [opts.entry];
@@ -98,7 +99,45 @@ function scan(opts) {
98
99
  const pkgPath = utils_1.pkgUp.sync({ cwd: resolved });
99
100
  (0, assert_1.default)(pkgPath, `package.json for found for ${resolved}`);
100
101
  const pkg = require(pkgPath);
101
- ret[pkg.name] = pkg.version;
102
+ const entryResolved = yield opts.resolver
103
+ .resolve((0, path_1.dirname)(pkgPath), pkg.name)
104
+ // alias may resolve error (eg: dva from @umijs/plugins)
105
+ // fallback to null for mark it as subpath usage
106
+ .catch(() => null);
107
+ const isSubpath = entryResolved !== resolved;
108
+ ret[pkg.name] = {
109
+ version: pkg.version,
110
+ // collect entry matches
111
+ matches: [
112
+ // avoid duplicate
113
+ ...new Set([
114
+ ...(((_a = ret[pkg.name]) === null || _a === void 0 ? void 0 : _a.matches) || []),
115
+ // only collect non-subpath matches
116
+ ...(!isSubpath
117
+ ? [
118
+ // match origin path from source code
119
+ dep.url,
120
+ // match resolved absolute path
121
+ resolved,
122
+ // match no ext name path
123
+ resolved.replace(/\/\.[^\.]+$/, ''),
124
+ // match parent dir for index module
125
+ ...(/\/index[^\/]+$/.test(resolved)
126
+ ? [(0, path_1.dirname)(resolved)]
127
+ : []),
128
+ ]
129
+ : []),
130
+ ]),
131
+ ],
132
+ // collect subpath matches
133
+ subpaths: [
134
+ // avoid duplicate
135
+ ...new Set([
136
+ ...(((_b = ret[pkg.name]) === null || _b === void 0 ? void 0 : _b.subpaths) || []),
137
+ ...(isSubpath ? [dep.url] : []),
138
+ ]),
139
+ ],
140
+ };
102
141
  }
103
142
  else if (['.ts', '.tsx', '.js', '.jsx', '.mjs'].includes((0, path_1.extname)(resolved))) {
104
143
  queueDeps.push(resolved);
@@ -7,8 +7,8 @@ const utils_1 = require("@umijs/utils");
7
7
  const assert_1 = __importDefault(require("assert"));
8
8
  const fs_1 = require("fs");
9
9
  const path_1 = require("path");
10
- const transformIEAR_1 = __importDefault(require("./utils/transformIEAR"));
11
10
  const isTypeScriptFile_1 = require("./utils/isTypeScriptFile");
11
+ const transformIEAR_1 = __importDefault(require("./utils/transformIEAR"));
12
12
  exports.default = (api) => {
13
13
  [
14
14
  'onGenerateFiles',
@@ -84,10 +84,14 @@ function transformIEAR({ content, path }, api) {
84
84
  return content.replace(exports.IEAR_REG_EXP, (_, prefix, quote, absPath) => {
85
85
  if (absPath.startsWith(api.paths.absTmpPath)) {
86
86
  // transform .umi absolute imports
87
- absPath = (0, utils_1.winPath)((0, path_1.relative)((0, path_1.dirname)(path), absPath));
87
+ absPath = (0, utils_1.winPath)((0, path_1.relative)((0, path_1.dirname)(path), absPath)).replace(
88
+ // prepend ./ for same or sub level imports
89
+ /^(?!\.\.\/)/, './');
88
90
  }
89
91
  else if (absPath.includes('node_modules')) {
90
92
  // transform node_modules absolute imports
93
+ // why @fs
94
+ // 由于我们临时文件下大量绝对路径的引用,而绝对路径的引用不会被 Vite 预编译
91
95
  absPath = `@fs${absPath}`;
92
96
  }
93
97
  return `${prefix}${quote}${absPath}${quote}`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/preset-umi",
3
- "version": "4.0.0-beta.15",
3
+ "version": "4.0.0-beta.16",
4
4
  "description": "@umijs/preset-umi",
5
5
  "homepage": "https://github.com/umijs/umi-next/tree/master/packages/preset-umi#readme",
6
6
  "bugs": "https://github.com/umijs/umi-next/issues",
@@ -24,21 +24,22 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@types/multer": "1.4.7",
27
- "@umijs/ast": "4.0.0-beta.15",
28
- "@umijs/babel-preset-umi": "4.0.0-beta.15",
29
- "@umijs/bundler-utils": "4.0.0-beta.15",
30
- "@umijs/bundler-vite": "4.0.0-beta.15",
31
- "@umijs/bundler-webpack": "4.0.0-beta.15",
32
- "@umijs/core": "4.0.0-beta.15",
33
- "@umijs/renderer-react": "4.0.0-beta.15",
34
- "@umijs/server": "4.0.0-beta.15",
35
- "@umijs/utils": "4.0.0-beta.15",
27
+ "@umijs/ast": "4.0.0-beta.16",
28
+ "@umijs/babel-preset-umi": "4.0.0-beta.16",
29
+ "@umijs/bundler-utils": "4.0.0-beta.16",
30
+ "@umijs/bundler-vite": "4.0.0-beta.16",
31
+ "@umijs/bundler-webpack": "4.0.0-beta.16",
32
+ "@umijs/core": "4.0.0-beta.16",
33
+ "@umijs/renderer-react": "4.0.0-beta.16",
34
+ "@umijs/server": "4.0.0-beta.16",
35
+ "@umijs/utils": "4.0.0-beta.16",
36
+ "core-js": "3.19.2",
36
37
  "current-script-polyfill": "1.0.0",
37
38
  "enhanced-resolve": "5.8.3",
38
39
  "magic-string": "0.25.7",
39
40
  "path-to-regexp": "1.7.0",
40
- "react": "18.0.0-rc.0",
41
- "react-dom": "18.0.0-rc.0",
41
+ "react": "17.0.2",
42
+ "react-dom": "17.0.2",
42
43
  "react-router": "6.1.1",
43
44
  "react-router-dom": "6.1.1"
44
45
  },
@@ -0,0 +1,15 @@
1
+ import { createHashHistory, createMemoryHistory, createBrowserHistory, History } from '{{{ rendererPath }}}';
2
+
3
+ let history: History;
4
+ export function createHistory(opts: any) {
5
+ if (opts.type === 'hash') {
6
+ history = createHashHistory();
7
+ } else if (opts.type === 'memory') {
8
+ history = createMemoryHistory();
9
+ } else {
10
+ history = createBrowserHistory();
11
+ }
12
+ return history;
13
+ }
14
+
15
+ export { history };
package/templates/umi.tpl CHANGED
@@ -3,6 +3,7 @@
3
3
  import { renderClient } from '{{{ rendererPath }}}';
4
4
  import { getRoutes } from './core/route';
5
5
  import { createPluginManager } from './core/plugin';
6
+ import { createHistory } from './core/history';
6
7
  import { ApplyPluginsType, PluginManager } from 'umi';
7
8
  {{{ imports }}}
8
9
 
@@ -24,6 +25,9 @@ async function render() {
24
25
  routeComponents,
25
26
  pluginManager,
26
27
  rootElement: document.getElementById('{{{ mountElementId }}}'),
28
+ history: createHistory({
29
+ type: '{{{ historyType }}}',
30
+ }),
27
31
  {{#basename}}
28
32
  basename: '{{{ basename }}}',
29
33
  {{/basename}}