@umijs/preset-umi 4.2.15 → 4.3.0

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.
@@ -113,7 +113,10 @@ umi build --clean
113
113
  react: {
114
114
  runtime: shouldUseAutomaticRuntime ? "automatic" : "classic"
115
115
  },
116
- config: api.config,
116
+ config: {
117
+ outputPath: api.userConfig.outputPath || "dist",
118
+ ...api.config
119
+ },
117
120
  cwd: api.cwd,
118
121
  entry,
119
122
  ...api.config.vite ? { modifyViteConfig } : { babelPreset, chainWebpack, modifyWebpackConfig },
@@ -138,7 +141,7 @@ umi build --clean
138
141
  let stats;
139
142
  if (api.config.vite) {
140
143
  stats = await bundlerVite.build(opts);
141
- } else if (process.env.OKAM) {
144
+ } else if (api.config.mako) {
142
145
  require("@umijs/bundler-webpack/dist/requireHook");
143
146
  const { build } = require(process.env.OKAM);
144
147
  stats = await build(opts);
@@ -164,13 +167,13 @@ umi build --clean
164
167
  publicPath: api.config.publicPath
165
168
  });
166
169
  const { vite } = api.args;
167
- const markupArgs = await (0, import_getMarkupArgs.getMarkupArgs)({ api });
170
+ const args = await (0, import_getMarkupArgs.getMarkupArgs)({ api });
168
171
  const finalMarkUpArgs = {
169
- ...markupArgs,
170
- styles: markupArgs.styles.concat(
172
+ ...args,
173
+ styles: args.styles.concat(
171
174
  api.config.vite ? [] : [...(assetsMap["umi.css"] || []).map((src) => ({ src }))]
172
175
  ),
173
- scripts: (api.config.vite ? [] : [...(assetsMap["umi.js"] || []).map((src) => ({ src }))]).concat(markupArgs.scripts),
176
+ scripts: (api.config.vite ? [] : [...(assetsMap["umi.js"] || []).map((src) => ({ src }))]).concat(args.scripts),
174
177
  esmScript: !!opts.config.esm || vite,
175
178
  path: "/"
176
179
  };
@@ -33,8 +33,8 @@ function createRouteMiddleware(opts) {
33
33
  webpackStats = stats;
34
34
  onStats == null ? void 0 : onStats(stats);
35
35
  });
36
- async function getStats() {
37
- if (!compiler && process.env.OKAM) {
36
+ async function getStats(api) {
37
+ if (!compiler && api.config.mako) {
38
38
  return {
39
39
  compilation: { assets: { "umi.js": "umi.js", "umi.css": "umi.css" } },
40
40
  hasErrors: () => false
@@ -52,7 +52,7 @@ function createRouteMiddleware(opts) {
52
52
  var _a;
53
53
  const markupArgs = await (0, import_getMarkupArgs.getMarkupArgs)(opts);
54
54
  let assetsMap = {};
55
- const stats = await getStats();
55
+ const stats = await getStats(opts.api);
56
56
  assetsMap = (0, import_getAssetsMap.getAssetsMap)({
57
57
  stats,
58
58
  publicPath: opts.api.config.publicPath
@@ -315,7 +315,10 @@ PORT=8888 umi dev
315
315
  react: {
316
316
  runtime: shouldUseAutomaticRuntime ? "automatic" : "classic"
317
317
  },
318
- config: api.config,
318
+ config: {
319
+ outputPath: api.userConfig.outputPath || "dist",
320
+ ...api.config
321
+ },
319
322
  pkg: api.pkg,
320
323
  cwd: api.cwd,
321
324
  rootDir: process.cwd(),
@@ -384,7 +387,7 @@ PORT=8888 umi dev
384
387
  });
385
388
  if (enableVite) {
386
389
  await bundlerVite.dev(opts);
387
- } else if (process.env.OKAM) {
390
+ } else if (api.config.mako) {
388
391
  require("@umijs/bundler-webpack/dist/requireHook");
389
392
  const { dev } = require(process.env.OKAM);
390
393
  await dev(opts);
@@ -25,9 +25,11 @@ module.exports = __toCommonJS(umiInfo_exports);
25
25
  var umiInfo_default = (api) => {
26
26
  api.addEntryCode(() => [
27
27
  `
28
- window.g_umi = {
29
- version: '${api.appData.umi.version}',
30
- };
31
- `
28
+ if (typeof window !== 'undefined') {
29
+ window.g_umi = {
30
+ version: '${api.appData.umi.version}',
31
+ };
32
+ }
33
+ `
32
34
  ]);
33
35
  };
@@ -29,7 +29,7 @@ var devToolAppDist = (0, import_path.join)(__dirname, "../../../devToolAppDist")
29
29
  var assetsDir = (0, import_path.join)(__dirname, "../../../assets");
30
30
  var devTool_default = (api) => {
31
31
  api.addBeforeMiddlewares(async () => {
32
- if (process.env.OKAM)
32
+ if (api.config.mako)
33
33
  return [];
34
34
  const $ = await api.applyPlugins({
35
35
  key: "modifyDevToolLoadingHTML",
@@ -109,9 +109,7 @@ var esbuildHelperChecker_default = (api) => {
109
109
  }
110
110
  });
111
111
  api.onBuildComplete(async ({ err }) => {
112
- if (api.config.vite)
113
- return;
114
- if (process.env.OKAM)
112
+ if (api.config.vite || api.config.mako)
115
113
  return;
116
114
  if (err)
117
115
  return;
@@ -64,23 +64,14 @@ function getExportHtmlData(routes) {
64
64
  return Array.from(map.values());
65
65
  }
66
66
  async function getPreRenderedHTML(api, htmlTpl, path) {
67
- var _a, _b;
68
67
  const {
69
68
  exportStatic: { ignorePreRenderError = false }
70
69
  } = api.config;
71
70
  markupRender ?? (markupRender = require((0, import_utils2.absServerBuildPath)(api))._markupGenerator);
72
71
  try {
73
- const markup = await markupRender(path);
74
- const [mainTpl, extraTpl = ""] = markup.split("</html>");
75
- const helmetContent = (_a = mainTpl.match(
76
- /<head>[^]*?(<[^>]+data-rh[^]+)<\/head>/
77
- )) == null ? void 0 : _a[1];
78
- const bodyContent = (_b = mainTpl.match(/<body[^>]*>([^]+?)<\/body>/)) == null ? void 0 : _b[1];
79
- htmlTpl = htmlTpl.replace("</head>", `${helmetContent || ""}</head>`).replace(
80
- new RegExp(`<div id="${api.config.mountElementId}"[^>]*>.*?</div>`),
81
- bodyContent
82
- ).replace(/$/, `${extraTpl}`);
72
+ const html = await markupRender(path);
83
73
  import_utils.logger.info(`Pre-render for ${path}`);
74
+ return html;
84
75
  } catch (err) {
85
76
  import_utils.logger.error(`Pre-render ${path} error: ${err}`);
86
77
  if (!ignorePreRenderError) {
@@ -125,17 +116,8 @@ var exportStatic_default = (api) => {
125
116
  const htmlData = api.appData.exportHtmlData;
126
117
  const htmlFiles = [];
127
118
  const { markupArgs: defaultMarkupArgs } = opts;
128
- let asyncMarkupArgs;
129
119
  for (const { file, route, prerender } of htmlData) {
130
120
  let markupArgs = defaultMarkupArgs;
131
- if (api.config.ssr && prerender) {
132
- markupArgs = asyncMarkupArgs ?? (asyncMarkupArgs = {
133
- ...markupArgs,
134
- scripts: markupArgs.scripts.map(
135
- (script) => script.src ? { ...script, async: true } : script
136
- )
137
- });
138
- }
139
121
  if (publicPath.startsWith(".")) {
140
122
  (0, import_assert.default)(
141
123
  api.config.runtimePublicPath,
@@ -32,23 +32,37 @@ __export(mako_exports, {
32
32
  default: () => mako_default
33
33
  });
34
34
  module.exports = __toCommonJS(mako_exports);
35
- var import_path = __toESM(require("path"));
36
35
  var import_utils = require("@umijs/utils");
36
+ var import_path = __toESM(require("path"));
37
+ var import_platform = require("../../utils/platform");
37
38
  var mako_default = (api) => {
38
39
  api.describe({
39
40
  key: "mako",
40
41
  config: {
41
42
  schema({ zod }) {
42
- return zod.object({});
43
+ return zod.object({
44
+ plugins: zod.array(
45
+ zod.object({
46
+ load: zod.function(),
47
+ generateEnd: zod.function()
48
+ }).partial()
49
+ )
50
+ }).partial();
43
51
  }
44
52
  },
45
53
  enableBy: api.EnableBy.config
46
54
  });
47
55
  api.modifyConfig((memo) => {
56
+ var _a;
57
+ if (import_platform.isWindows) {
58
+ memo.mako = false;
59
+ process.env.OKAM = "";
60
+ }
48
61
  return {
49
62
  ...memo,
50
63
  mfsu: false,
51
- hmrGuardian: false
64
+ hmrGuardian: false,
65
+ makoPlugins: ((_a = memo.mako) == null ? void 0 : _a.plugins) || []
52
66
  };
53
67
  });
54
68
  api.onStart(() => {
@@ -61,7 +75,13 @@ var mako_default = (api) => {
61
75
  api.logger.info(`Using mako@${pkg.version}`);
62
76
  const isBigfish = process.env.BIGFISH_INFO;
63
77
  if (!isBigfish) {
64
- api.logger.warn(import_utils.chalk.yellow(import_utils.chalk.bold(`Mako is an extremely fast, production-grade web bundler based on Rust. And it's still under active development and is not yet ready for production use. If you encounter any issues, please checkout https://makojs.dev/ to join the community and report the issue.`)));
78
+ api.logger.warn(
79
+ import_utils.chalk.yellow(
80
+ import_utils.chalk.bold(
81
+ `Mako is an extremely fast, production-grade web bundler based on Rust. And it's still under active development and is not yet ready for production use. If you encounter any issues, please checkout https://makojs.dev/ to join the community and report the issue.`
82
+ )
83
+ )
84
+ );
65
85
  }
66
86
  } catch (e) {
67
87
  console.error(e);
@@ -25,7 +25,7 @@ module.exports = __toCommonJS(okam_exports);
25
25
  var import_utils = require("@umijs/utils");
26
26
  var okam_default = (api) => {
27
27
  api.describe({
28
- enableBy: () => Boolean(process.env.OKAM)
28
+ enableBy: () => Boolean(api.config.mako)
29
29
  });
30
30
  api.onCheck(() => {
31
31
  (0, import_utils.checkVersion)(16, `Node 16 is required when using mako.`);
@@ -0,0 +1 @@
1
+ export declare const build: (api: IApi) => Promise<void>;
@@ -0,0 +1,95 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/features/ssr/mako/mako.ts
30
+ var mako_exports = {};
31
+ __export(mako_exports, {
32
+ build: () => build
33
+ });
34
+ module.exports = __toCommonJS(mako_exports);
35
+ var import_types = require("@umijs/bundler-webpack/dist/types");
36
+ var import_utils = require("@umijs/utils");
37
+ var import_lodash = require("@umijs/utils/compiled/lodash");
38
+ var import_fs = require("fs");
39
+ var import_path = __toESM(require("path"));
40
+ var import_utils2 = require("../utils");
41
+ var build = async (api) => {
42
+ import_utils.logger.wait("[SSR] Compiling by mako...");
43
+ const now = (/* @__PURE__ */ new Date()).getTime();
44
+ const absOutputFile = (0, import_utils2.absServerBuildPath)(api);
45
+ require("@umijs/bundler-webpack/dist/requireHook");
46
+ const { build: build2 } = require(process.env.OKAM);
47
+ const useHash = api.config.hash && api.env === import_types.Env.production;
48
+ const publicPath = api.userConfig.publicPath || "/";
49
+ const entry = import_path.default.resolve(api.paths.absTmpPath, "umi.server.ts");
50
+ const options = {
51
+ cwd: api.cwd,
52
+ entry: {
53
+ "umi.server": entry
54
+ },
55
+ config: {
56
+ makoPlugins: api.config.mako.plugins,
57
+ ...api.config,
58
+ jsMinifier: "none",
59
+ hash: useHash,
60
+ outputPath: import_path.default.dirname(absOutputFile),
61
+ manifest: {
62
+ fileName: "build-manifest.json"
63
+ },
64
+ devtool: false,
65
+ cjs: true,
66
+ dynamicImportToRequire: false
67
+ },
68
+ chainWebpack: async (memo) => {
69
+ memo.target("node");
70
+ return memo;
71
+ },
72
+ onBuildComplete: () => {
73
+ const finalJsonObj = {};
74
+ const jsonFilePath = (0, import_path.join)((0, import_path.dirname)(absOutputFile), "build-manifest.json");
75
+ const json = (0, import_fs.existsSync)(jsonFilePath) ? import_utils.fsExtra.readJSONSync(jsonFilePath) : {};
76
+ (0, import_lodash.forEach)(json, (path2, key) => {
77
+ json[key] = `${publicPath}${path2}`;
78
+ });
79
+ finalJsonObj.assets = {
80
+ ...json,
81
+ "umi.js": json["umi.server.js"]
82
+ };
83
+ (0, import_fs.writeFileSync)(jsonFilePath, JSON.stringify(finalJsonObj, null, 2), {
84
+ flag: "w"
85
+ });
86
+ }
87
+ };
88
+ await build2(options);
89
+ const diff = (/* @__PURE__ */ new Date()).getTime() - now;
90
+ import_utils.logger.info(`[SSR] Compiled in ${diff}ms`);
91
+ };
92
+ // Annotate the CommonJS export names for ESM import in node:
93
+ 0 && (module.exports = {
94
+ build
95
+ });
@@ -37,6 +37,7 @@ var import_utils = require("@umijs/utils");
37
37
  var import_assert = __toESM(require("assert"));
38
38
  var import_fs = require("fs");
39
39
  var import_path = require("path");
40
+ var import_platform = require("../../utils/platform");
40
41
  var import_utils2 = require("./utils");
41
42
  var ssr_default = (api) => {
42
43
  const esbuildBuilder = (0, import_utils.importLazy)(
@@ -45,14 +46,23 @@ var ssr_default = (api) => {
45
46
  const webpackBuilder = (0, import_utils.importLazy)(
46
47
  require.resolve("./webpack/webpack")
47
48
  );
49
+ const makoBuiler = (0, import_utils.importLazy)(
50
+ require.resolve("./mako/mako")
51
+ );
52
+ let serverBuildTarget;
48
53
  api.describe({
49
54
  key: "ssr",
50
55
  config: {
51
56
  schema({ zod }) {
52
57
  return zod.object({
53
58
  serverBuildPath: zod.string(),
59
+ serverBuildTarget: zod.enum(["express", "worker"]),
54
60
  platform: zod.string(),
55
- builder: zod.enum(["esbuild", "webpack"])
61
+ builder: zod.enum(["esbuild", "webpack", "mako"]),
62
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: zod.object({
63
+ pureApp: zod.boolean(),
64
+ pureHtml: zod.boolean()
65
+ })
56
66
  }).deepPartial();
57
67
  }
58
68
  },
@@ -69,6 +79,35 @@ var ssr_default = (api) => {
69
79
  api.onStart(() => {
70
80
  import_utils.logger.warn(`SSR feature is in beta, may be unstable`);
71
81
  });
82
+ api.modifyDefaultConfig((memo) => {
83
+ if (serverBuildTarget === "worker") {
84
+ const oReactDom = memo.alias["react-dom"];
85
+ delete memo.alias["react-dom"];
86
+ memo.alias["react-dom/server$"] = (0, import_utils.winPath)(
87
+ (0, import_path.join)(
88
+ api.service.configDefaults.alias["react-dom"],
89
+ "server.browser.js"
90
+ )
91
+ );
92
+ memo.alias["react-dom"] = oReactDom;
93
+ }
94
+ return memo;
95
+ });
96
+ api.modifyConfig((memo) => {
97
+ memo.define ?? (memo.define = {});
98
+ serverBuildTarget = memo.define["process.env.SSR_BUILD_TARGET"] = memo.ssr.serverBuildTarget || "express";
99
+ if (memo.ssr.builder === "mako") {
100
+ (0, import_assert.default)(
101
+ memo.mako,
102
+ `The \`ssr.builder mako\` config is now allowed when \`mako\` is enable!`
103
+ );
104
+ memo.manifest ?? (memo.manifest = {});
105
+ if (import_platform.isWindows) {
106
+ memo.ssr.builder = "webpack";
107
+ }
108
+ }
109
+ return memo;
110
+ });
72
111
  api.addMiddlewares(() => [
73
112
  async (req, res, next) => {
74
113
  const modulePath = (0, import_utils2.absServerBuildPath)(api);
@@ -133,7 +172,7 @@ export type {
133
172
  });
134
173
  });
135
174
  api.onBeforeCompiler(async ({ opts }) => {
136
- const { builder = "esbuild" } = api.config.ssr;
175
+ const { builder = "webpack" } = api.config.ssr;
137
176
  if (builder === "esbuild") {
138
177
  await esbuildBuilder.build({
139
178
  api,
@@ -145,6 +184,18 @@ export type {
145
184
  `The \`vite\` config is now allowed when \`ssr.builder\` is webpack!`
146
185
  );
147
186
  await webpackBuilder.build(api, opts);
187
+ } else if (api.config.mako && builder === "mako") {
188
+ await makoBuiler.build(api);
189
+ }
190
+ });
191
+ api.onDevCompileDone(() => {
192
+ if (api.config.mako) {
193
+ (0, import_utils2.generateBuildManifest)(api);
194
+ }
195
+ });
196
+ api.onBuildComplete(() => {
197
+ if (api.config.mako) {
198
+ (0, import_utils2.generateBuildManifest)(api);
148
199
  }
149
200
  });
150
201
  api.onBuildComplete(async ({ err }) => {
@@ -5,3 +5,4 @@ export declare function esbuildUmiPlugin(api: IApi): {
5
5
  setup(build: any): void;
6
6
  };
7
7
  export declare function absServerBuildPath(api: IApi): string;
8
+ export declare const generateBuildManifest: (api: IApi) => void;
@@ -20,9 +20,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  var utils_exports = {};
21
21
  __export(utils_exports, {
22
22
  absServerBuildPath: () => absServerBuildPath,
23
- esbuildUmiPlugin: () => esbuildUmiPlugin
23
+ esbuildUmiPlugin: () => esbuildUmiPlugin,
24
+ generateBuildManifest: () => generateBuildManifest
24
25
  });
25
26
  module.exports = __toCommonJS(utils_exports);
27
+ var import_utils = require("@umijs/utils");
28
+ var import_lodash = require("@umijs/utils/compiled/lodash");
26
29
  var import_fs = require("fs");
27
30
  var import_path = require("path");
28
31
  function esbuildUmiPlugin(api) {
@@ -53,8 +56,25 @@ function absServerBuildPath(api) {
53
56
  const manifest = require(manifestPath);
54
57
  return (0, import_path.join)(api.paths.cwd, "server", (0, import_path.basename)(manifest.assets["umi.js"]));
55
58
  }
59
+ var generateBuildManifest = (api) => {
60
+ var _a;
61
+ const publicPath = api.userConfig.publicPath || "/";
62
+ const manifestFileName = ((_a = api.config.manifest) == null ? void 0 : _a.fileName) || "asset-manifest.json";
63
+ const finalJsonObj = {};
64
+ const assetFilePath = (0, import_path.join)(api.paths.absOutputPath, manifestFileName);
65
+ const buildFilePath = (0, import_path.join)(api.paths.absOutputPath, "build-manifest.json");
66
+ const json = (0, import_fs.existsSync)(assetFilePath) ? import_utils.fsExtra.readJSONSync(assetFilePath) : {};
67
+ (0, import_lodash.forEach)(json, (path, key) => {
68
+ json[key] = `${publicPath}${path}`;
69
+ });
70
+ finalJsonObj.assets = json;
71
+ (0, import_fs.writeFileSync)(buildFilePath, JSON.stringify(finalJsonObj, null, 2), {
72
+ flag: "w"
73
+ });
74
+ };
56
75
  // Annotate the CommonJS export names for ESM import in node:
57
76
  0 && (module.exports = {
58
77
  absServerBuildPath,
59
- esbuildUmiPlugin
78
+ esbuildUmiPlugin,
79
+ generateBuildManifest
60
80
  });
@@ -36,6 +36,7 @@ var import_utils = require("@umijs/utils");
36
36
  var import_fs = require("fs");
37
37
  var import_path = require("path");
38
38
  var import_umi = require("umi");
39
+ var import_getMarkupArgs = require("../../commands/dev/getMarkupArgs");
39
40
  var import_constants = require("../../constants");
40
41
  var import_getModuleExports = require("./getModuleExports");
41
42
  var import_importsToStr = require("./importsToStr");
@@ -53,7 +54,7 @@ var tmpFiles_default = (api) => {
53
54
  }
54
55
  });
55
56
  api.onGenerateFiles(async (opts) => {
56
- var _a, _b, _c;
57
+ var _a, _b, _c, _d;
57
58
  const rendererPath = (0, import_utils.winPath)(
58
59
  await api.applyPlugins({
59
60
  key: "modifyRendererPath",
@@ -269,6 +270,37 @@ declare module '*.txt' {
269
270
  }
270
271
  `.trimEnd()
271
272
  });
273
+ const entryCode = (await api.applyPlugins({
274
+ key: "addEntryCode",
275
+ initialValue: []
276
+ })).join("\n");
277
+ const entryCodeAhead = (await api.applyPlugins({
278
+ key: "addEntryCodeAhead",
279
+ initialValue: []
280
+ })).join("\n");
281
+ const importsAhead = (0, import_importsToStr.importsToStr)(
282
+ await api.applyPlugins({
283
+ key: "addEntryImportsAhead",
284
+ initialValue: [
285
+ api.appData.globalCSS.length && {
286
+ source: api.appData.globalCSS[0]
287
+ },
288
+ api.appData.globalJS.length && {
289
+ source: api.appData.globalJS[0]
290
+ }
291
+ ].filter(Boolean)
292
+ })
293
+ ).join("\n");
294
+ const imports = (0, import_importsToStr.importsToStr)(
295
+ await api.applyPlugins({
296
+ key: "addEntryImports",
297
+ initialValue: []
298
+ })
299
+ ).join("\n");
300
+ const __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ((_b = api.config.ssr) == null ? void 0 : _b.__INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED) ?? {
301
+ pureApp: false,
302
+ pureHtml: false
303
+ };
272
304
  api.writeTmpFile({
273
305
  noPluginDir: true,
274
306
  path: "umi.ts",
@@ -278,41 +310,21 @@ declare module '*.txt' {
278
310
  rendererPath,
279
311
  publicPath: api.config.publicPath,
280
312
  runtimePublicPath: api.config.runtimePublicPath ? "true" : "false",
281
- entryCode: (await api.applyPlugins({
282
- key: "addEntryCode",
283
- initialValue: []
284
- })).join("\n"),
285
- entryCodeAhead: (await api.applyPlugins({
286
- key: "addEntryCodeAhead",
287
- initialValue: []
288
- })).join("\n"),
313
+ entryCode,
314
+ entryCodeAhead,
289
315
  polyfillImports: (0, import_importsToStr.importsToStr)(
290
316
  await api.applyPlugins({
291
317
  key: "addPolyfillImports",
292
318
  initialValue: []
293
319
  })
294
320
  ).join("\n"),
295
- importsAhead: (0, import_importsToStr.importsToStr)(
296
- await api.applyPlugins({
297
- key: "addEntryImportsAhead",
298
- initialValue: [
299
- api.appData.globalCSS.length && {
300
- source: api.appData.globalCSS[0]
301
- },
302
- api.appData.globalJS.length && {
303
- source: api.appData.globalJS[0]
304
- }
305
- ].filter(Boolean)
306
- })
307
- ).join("\n"),
308
- imports: (0, import_importsToStr.importsToStr)(
309
- await api.applyPlugins({
310
- key: "addEntryImports",
311
- initialValue: []
312
- })
313
- ).join("\n"),
321
+ importsAhead,
322
+ imports,
314
323
  basename: api.config.base,
315
324
  historyType: api.config.history.type,
325
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: JSON.stringify(
326
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
327
+ ),
316
328
  hydrate: !!api.config.ssr,
317
329
  reactRouter5Compat: !!api.config.reactRouter5Compat,
318
330
  loadingComponent: api.appData.globalLoading
@@ -343,7 +355,7 @@ export default function EmptyRoute() {
343
355
  }
344
356
  const hasSrc = api.appData.hasSrcDir;
345
357
  const pages = (0, import_path.basename)(
346
- ((_b = api.config.conventionRoutes) == null ? void 0 : _b.base) || api.paths.absPagesPath
358
+ ((_c = api.config.conventionRoutes) == null ? void 0 : _c.base) || api.paths.absPagesPath
347
359
  );
348
360
  const prefix = hasSrc ? `../../../src/${pages}/` : `../../${pages}/`;
349
361
  const clonedRoutes = import_utils.lodash.cloneDeep(routes);
@@ -401,7 +413,7 @@ if (process.env.NODE_ENV === 'development') {
401
413
  });
402
414
  const plugins = await api.applyPlugins({
403
415
  key: "addRuntimePlugin",
404
- initialValue: [(_c = api.appData.appJS) == null ? void 0 : _c.path].filter(Boolean)
416
+ initialValue: [(_d = api.appData.appJS) == null ? void 0 : _d.path].filter(Boolean)
405
417
  });
406
418
  function checkDuplicatePluginKeys(arr) {
407
419
  const duplicates = [];
@@ -460,6 +472,7 @@ if (process.env.NODE_ENV === 'development') {
460
472
  if (api.config.ssr) {
461
473
  const umiPluginPath = (0, import_utils.winPath)((0, import_path.join)(umiDir, "client/client/plugin.js"));
462
474
  const umiServerPath = (0, import_utils.winPath)(require.resolve("@umijs/server/dist/ssr"));
475
+ const mountElementId = api.config.mountElementId;
463
476
  const routesWithServerLoader = Object.keys(routes).reduce((memo, id) => {
464
477
  if (routes[id].hasServerLoader) {
465
478
  memo.push({
@@ -469,6 +482,7 @@ if (process.env.NODE_ENV === 'development') {
469
482
  }
470
483
  return memo;
471
484
  }, []);
485
+ const { headScripts, scripts, styles, title, favicons, links, metas } = await (0, import_getMarkupArgs.getMarkupArgs)({ api });
472
486
  api.writeTmpFile({
473
487
  noPluginDir: true,
474
488
  path: "umi.server.ts",
@@ -478,7 +492,13 @@ if (process.env.NODE_ENV === 'development') {
478
492
  /"component": "await import\((.*)\)"/g,
479
493
  '"component": await import("$1")'
480
494
  ),
495
+ version: api.appData.umi.version,
496
+ reactVersion: api.appData.react.version,
497
+ entryCode,
498
+ entryCodeAhead,
481
499
  routesWithServerLoader,
500
+ importsAhead,
501
+ imports,
482
502
  umiPluginPath,
483
503
  serverRendererPath,
484
504
  umiServerPath,
@@ -486,7 +506,20 @@ if (process.env.NODE_ENV === 'development') {
486
506
  assetsPath: (0, import_utils.winPath)(
487
507
  (0, import_path.join)(api.paths.absOutputPath, "build-manifest.json")
488
508
  ),
489
- env: JSON.stringify(api.env)
509
+ env: JSON.stringify(api.env),
510
+ htmlPageOpts: JSON.stringify({
511
+ headScripts,
512
+ styles,
513
+ title,
514
+ favicons,
515
+ links,
516
+ metas,
517
+ scripts: scripts || []
518
+ }),
519
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: JSON.stringify(
520
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
521
+ ),
522
+ mountElementId
490
523
  }
491
524
  });
492
525
  }
@@ -553,7 +586,9 @@ if (process.env.NODE_ENV === 'development') {
553
586
  exportMembers
554
587
  })).join(", ")} } from '${rendererPath}';`
555
588
  );
556
- exports.push(`export type { History } from '${rendererPath}'`);
589
+ exports.push(
590
+ `export type { History, ClientLoader } from '${rendererPath}'`
591
+ );
557
592
  exports.push("// umi/client/client/plugin");
558
593
  const umiPluginPath = (0, import_utils.winPath)((0, import_path.join)(umiDir, "client/client/plugin.js"));
559
594
  exports.push(
package/dist/types.d.ts CHANGED
@@ -117,6 +117,7 @@ export declare type IApi = PluginAPI & IServicePluginAPI & {
117
117
  (fn: {
118
118
  (memo: WebpackChain, args: {
119
119
  env: Env;
120
+ ssr?: boolean;
120
121
  webpack: typeof webpack;
121
122
  }): void;
122
123
  }): void;
@@ -0,0 +1 @@
1
+ export declare const isWindows: boolean;
@@ -0,0 +1,40 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+
29
+ // src/utils/platform.ts
30
+ var platform_exports = {};
31
+ __export(platform_exports, {
32
+ isWindows: () => isWindows
33
+ });
34
+ module.exports = __toCommonJS(platform_exports);
35
+ var import_os = __toESM(require("os"));
36
+ var isWindows = import_os.default.platform() === "win32";
37
+ // Annotate the CommonJS export names for ESM import in node:
38
+ 0 && (module.exports = {
39
+ isWindows
40
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/preset-umi",
3
- "version": "4.2.15",
3
+ "version": "4.3.0",
4
4
  "description": "@umijs/preset-umi",
5
5
  "homepage": "https://github.com/umijs/umi/tree/master/packages/preset-umi#readme",
6
6
  "bugs": "https://github.com/umijs/umi/issues",
@@ -21,7 +21,7 @@
21
21
  "dependencies": {
22
22
  "@iconify/utils": "2.1.1",
23
23
  "@svgr/core": "6.5.1",
24
- "@umijs/bundler-mako": "0.7.2",
24
+ "@umijs/bundler-mako": "0.7.3",
25
25
  "@umijs/es-module-parser": "0.0.7",
26
26
  "@umijs/history": "5.3.1",
27
27
  "babel-plugin-dynamic-import-node": "2.3.3",
@@ -36,26 +36,26 @@
36
36
  "path-to-regexp": "1.7.0",
37
37
  "postcss": "^8.4.21",
38
38
  "postcss-prefix-selector": "1.16.0",
39
- "react": "18.1.0",
40
- "react-dom": "18.1.0",
39
+ "react": "18.3.1",
40
+ "react-dom": "18.3.1",
41
41
  "react-router": "6.3.0",
42
42
  "react-router-dom": "6.3.0",
43
43
  "regenerator-runtime": "0.13.11",
44
- "@umijs/ast": "4.2.15",
45
- "@umijs/bundler-vite": "4.2.15",
46
- "@umijs/babel-preset-umi": "4.2.15",
47
- "@umijs/bundler-esbuild": "4.2.15",
48
- "@umijs/bundler-utils": "4.2.15",
49
- "@umijs/bundler-webpack": "4.2.15",
50
- "@umijs/mfsu": "4.2.15",
51
- "@umijs/core": "4.2.15",
52
- "@umijs/plugin-run": "4.2.15",
53
- "@umijs/renderer-react": "4.2.15",
54
- "@umijs/utils": "4.2.15",
55
- "@umijs/zod2ts": "4.2.15",
56
- "@umijs/ui": "3.0.1",
57
- "@umijs/server": "4.2.15",
58
- "@umijs/did-you-know": "1.0.3"
44
+ "@umijs/ast": "4.3.0",
45
+ "@umijs/babel-preset-umi": "4.3.0",
46
+ "@umijs/bundler-esbuild": "4.3.0",
47
+ "@umijs/bundler-utils": "4.3.0",
48
+ "@umijs/bundler-vite": "4.3.0",
49
+ "@umijs/bundler-webpack": "4.3.0",
50
+ "@umijs/core": "4.3.0",
51
+ "@umijs/mfsu": "4.3.0",
52
+ "@umijs/plugin-run": "4.3.0",
53
+ "@umijs/utils": "4.3.0",
54
+ "@umijs/zod2ts": "4.3.0",
55
+ "@umijs/server": "4.3.0",
56
+ "@umijs/did-you-know": "1.0.3",
57
+ "@umijs/renderer-react": "4.3.0",
58
+ "@umijs/ui": "3.0.1"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@manypkg/get-packages": "1.1.3",
@@ -1,11 +1,14 @@
1
+ {{{ importsAhead }}}
1
2
  import { getClientRootComponent } from '{{{ serverRendererPath }}}';
2
3
  import { getRoutes } from './core/route';
3
4
  import { createHistory as createClientHistory } from './core/history';
4
- import { getPlugins as getClientPlugins } from './core/plugin';
5
5
  import { ServerInsertedHTMLContext } from './core/serverInsertedHTMLContext';
6
- import { PluginManager } from '{{{ umiPluginPath }}}';
7
- import createRequestHandler, { createMarkupGenerator, createUmiHandler, createUmiServerLoader } from '{{{ umiServerPath }}}';
8
-
6
+ import { createPluginManager } from './core/plugin';
7
+ import createRequestHandler, { createMarkupGenerator, createUmiHandler, createUmiServerLoader, createAppRootElement } from '{{{ umiServerPath }}}';
8
+ import fs from 'fs';
9
+ import path from 'path';
10
+ {{{ imports }}}
11
+ {{{ entryCodeAhead }}}
9
12
  let helmetContext;
10
13
 
11
14
  try {
@@ -18,17 +21,23 @@ const routesWithServerLoader = {
18
21
  {{/routesWithServerLoader}}
19
22
  };
20
23
 
21
- export function getPlugins() {
22
- return getClientPlugins();
23
- }
24
-
25
- export function getValidKeys() {
26
- return [{{#validKeys}}'{{{ . }}}',{{/validKeys}}];
27
- }
28
-
29
24
  export function getManifest(sourceDir) {
30
- return JSON.parse(require('fs').readFileSync(
31
- sourceDir ? require('path').join(sourceDir,'build-manifest.json') : '{{{ assetsPath }}}', 'utf-8'));
25
+ let manifestPath;
26
+ if (process.env.SSR_MANIFEST) {
27
+ return JSON.parse(process.env.SSR_MANIFEST)
28
+ }
29
+ if (sourceDir) {
30
+ manifestPath = path.join(sourceDir,'build-manifest.json')
31
+ }
32
+ else {
33
+ manifestPath = '{{{ assetsPath }}}'
34
+ }
35
+ if (fs.existsSync(manifestPath)) {
36
+ return JSON.parse(fs.readFileSync(manifestPath), 'utf-8');
37
+ }
38
+ return {
39
+ assets: {}
40
+ }
32
41
  }
33
42
 
34
43
  export function createHistory(opts) {
@@ -42,20 +51,35 @@ global.g_getAssets = (fileName) => {
42
51
  };
43
52
  const createOpts = {
44
53
  routesWithServerLoader,
45
- PluginManager,
46
- getPlugins,
47
- getValidKeys,
54
+ reactVersion: '{{{reactVersion}}}',
55
+ pluginManager: createPluginManager(),
48
56
  getRoutes,
49
57
  manifest: getManifest,
50
58
  getClientRootComponent,
51
59
  helmetContext,
52
60
  createHistory,
53
61
  ServerInsertedHTMLContext,
62
+ htmlPageOpts: {{{htmlPageOpts}}},
63
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {{{__INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED}}},
64
+ mountElementId: '{{{mountElementId}}}'
65
+
54
66
  };
55
67
  const requestHandler = createRequestHandler(createOpts);
68
+ /**
69
+ * @deprecated Please use `requestHandler` instead.
70
+ */
56
71
  export const renderRoot = createUmiHandler(createOpts);
72
+ /**
73
+ * @deprecated Please use `requestHandler` instead.
74
+ */
57
75
  export const serverLoader = createUmiServerLoader(createOpts);
58
76
 
59
77
  export const _markupGenerator = createMarkupGenerator(createOpts);
60
78
 
79
+ export const getAppRootElement = createAppRootElement.bind(null, createOpts)();
80
+
61
81
  export default requestHandler;
82
+
83
+ export const g_umi = '{{{version}}}'
84
+
85
+ {{{ entryCode }}}
package/templates/umi.tpl CHANGED
@@ -56,6 +56,7 @@ async function render() {
56
56
  routes,
57
57
  routeComponents,
58
58
  pluginManager,
59
+ mountElementId: '{{{mountElementId}}}',
59
60
  rootElement: contextOpts.rootElement || document.getElementById('{{{ mountElementId }}}'),
60
61
  {{#loadingComponent}}
61
62
  loadingComponent: Loading,
@@ -65,6 +66,7 @@ async function render() {
65
66
  history,
66
67
  historyType,
67
68
  basename,
69
+ __INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: {{{__INTERNAL_DO_NOT_USE_OR_YOU_WILL_BE_FIRED}}},
68
70
  callback: contextOpts.callback,
69
71
  };
70
72
  const modifiedContext = pluginManager.applyPlugins({