@umijs/bundler-utoopack 4.6.51 → 4.6.53

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/config.d.ts CHANGED
@@ -3,6 +3,10 @@ import type { BundleOptions } from '@utoo/pack';
3
3
  import type { IOpts } from './types';
4
4
  export declare function mergeExtraPostcssPlugins(postcssConfig: any, extraPlugins?: any[]): any;
5
5
  export declare function getProdUtooPackConfig(opts: IOpts): Promise<BundleOptions>;
6
+ export declare function getSSRUtooPackConfig(opts: IOpts & {
7
+ serverBuildPath: string;
8
+ useHash?: boolean;
9
+ }): Promise<BundleOptions>;
6
10
  export declare type IDevOpts = {
7
11
  afterMiddlewares?: any[];
8
12
  beforeMiddlewares?: any[];
package/dist/config.js CHANGED
@@ -31,6 +31,7 @@ var config_exports = {};
31
31
  __export(config_exports, {
32
32
  getDevUtooPackConfig: () => getDevUtooPackConfig,
33
33
  getProdUtooPackConfig: () => getProdUtooPackConfig,
34
+ getSSRUtooPackConfig: () => getSSRUtooPackConfig,
34
35
  mergeExtraPostcssPlugins: () => mergeExtraPostcssPlugins
35
36
  });
36
37
  module.exports = __toCommonJS(config_exports);
@@ -39,15 +40,24 @@ var import_utils = require("@umijs/utils");
39
40
  var import_pack = require("@utoo/pack");
40
41
  var import_fs = __toESM(require("fs"));
41
42
  var import_path = require("path");
42
- function normalizeDefineValue(val) {
43
- if (!import_utils.lodash.isPlainObject(val)) {
44
- return JSON.stringify(val);
45
- } else {
46
- return Object.keys(val).reduce((obj, key) => {
47
- obj[key] = normalizeDefineValue(val[key]);
48
- return obj;
49
- }, {});
43
+ function getUtoopackDefine(opts) {
44
+ const define = Object.fromEntries(
45
+ Object.entries(opts.config.define || {}).map(([key, value]) => {
46
+ return [key, normalizeUtoopackDefineValue(value)];
47
+ })
48
+ );
49
+ if (process.env.SOCKET_SERVER) {
50
+ define["process.env.SOCKET_SERVER"] = JSON.stringify(
51
+ process.env.SOCKET_SERVER
52
+ );
53
+ }
54
+ return define;
55
+ }
56
+ function normalizeUtoopackDefineValue(value) {
57
+ if (typeof value === "string") {
58
+ return JSON.stringify(value);
50
59
  }
60
+ return value;
51
61
  }
52
62
  function getModularizeImports(extraBabelPlugins) {
53
63
  return extraBabelPlugins.filter((p) => /^import$|babel-plugin-import/.test(p[0])).reduce(
@@ -88,6 +98,103 @@ function getModularizeImports(extraBabelPlugins) {
88
98
  {}
89
99
  );
90
100
  }
101
+ function getBabelPluginName(plugin) {
102
+ const name = Array.isArray(plugin) ? plugin[0] : plugin;
103
+ return typeof name === "string" ? name : "";
104
+ }
105
+ function isModularizeImportPlugin(plugin) {
106
+ return /^import$|babel-plugin-import/.test(getBabelPluginName(plugin));
107
+ }
108
+ function isEmotionBabelPlugin(plugin) {
109
+ const name = getBabelPluginName(plugin);
110
+ return name === "@emotion" || name.endsWith("@emotion/babel-plugin");
111
+ }
112
+ function getExtraBabelPlugins(opts) {
113
+ return [
114
+ ...opts.beforeBabelPlugins || [],
115
+ ...opts.extraBabelPlugins || [],
116
+ ...opts.config.extraBabelPlugins || []
117
+ ].filter(Boolean).filter(isSerializableBabelItem);
118
+ }
119
+ function getExtraBabelPresets(opts) {
120
+ return [
121
+ ...opts.beforeBabelPresets || [],
122
+ ...opts.extraBabelPresets || [],
123
+ ...opts.config.extraBabelPresets || []
124
+ ].filter(Boolean).filter(isSerializableBabelItem);
125
+ }
126
+ function dropUndefinedValues(value) {
127
+ if (Array.isArray(value)) {
128
+ return value.map(dropUndefinedValues);
129
+ }
130
+ if (value && typeof value === "object") {
131
+ return Object.fromEntries(
132
+ Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, dropUndefinedValues(item)])
133
+ );
134
+ }
135
+ return value;
136
+ }
137
+ function isSerializableBabelItem(item) {
138
+ const normalized = dropUndefinedValues(item);
139
+ try {
140
+ return import_utils.lodash.isEqual(normalized, JSON.parse(JSON.stringify(normalized)));
141
+ } catch (e) {
142
+ return false;
143
+ }
144
+ }
145
+ function getExtraBabelModuleRules(opts) {
146
+ var _a;
147
+ if (((_a = opts.config.utoopack) == null ? void 0 : _a.babelLoader) !== true) {
148
+ return {};
149
+ }
150
+ const plugins = getExtraBabelPlugins(opts).filter((plugin) => {
151
+ return !isModularizeImportPlugin(plugin) && !isEmotionBabelPlugin(plugin);
152
+ });
153
+ const extraPresets = getExtraBabelPresets(opts);
154
+ if (!plugins.length && !extraPresets.length) {
155
+ return {};
156
+ }
157
+ const presets = [opts.babelPreset, ...extraPresets].filter(Boolean);
158
+ const rule = {
159
+ condition: {
160
+ all: [
161
+ { not: "foreign" },
162
+ {
163
+ not: {
164
+ path: /[\\/]src[\\/]\.umi(?:-[^\\/]*)?[\\/]/
165
+ }
166
+ }
167
+ ]
168
+ },
169
+ loaders: [
170
+ {
171
+ loader: require.resolve("@umijs/bundler-webpack/compiled/babel-loader"),
172
+ options: dropUndefinedValues({
173
+ sourceType: "unambiguous",
174
+ babelrc: false,
175
+ configFile: false,
176
+ cacheDirectory: false,
177
+ browserslistConfigFile: false,
178
+ targets: opts.config.targets,
179
+ customize: opts.config.babelLoaderCustomize,
180
+ presets,
181
+ plugins
182
+ })
183
+ }
184
+ ],
185
+ as: "*.js"
186
+ };
187
+ return {
188
+ module: {
189
+ rules: Object.fromEntries(
190
+ ["js", "mjs", "cjs", "jsx", "ts", "tsx"].map((ext) => [
191
+ `**/src/**/*.${ext}`,
192
+ rule
193
+ ])
194
+ )
195
+ }
196
+ };
197
+ }
91
198
  function getNormalizedAlias(alias, rootDir) {
92
199
  const newAlias = { ...alias };
93
200
  for (const [key, value] of Object.entries(newAlias)) {
@@ -241,7 +348,10 @@ function mergeExtraPostcssPlugins(postcssConfig, extraPlugins = []) {
241
348
  }, postcssConfig);
242
349
  }
243
350
  function getUserUtoopackConfig(utoopackConfig = {}) {
244
- return import_utils.lodash.omit(utoopackConfig, ["root"]);
351
+ return import_utils.lodash.omit(utoopackConfig, ["babelLoader", "root"]);
352
+ }
353
+ function getDefaultPersistentCaching() {
354
+ return process.platform !== "win32";
245
355
  }
246
356
  async function getProdUtooPackConfig(opts) {
247
357
  var _a;
@@ -279,17 +389,7 @@ async function getProdUtooPackConfig(opts) {
279
389
  const emotion = extraBabelPlugins.some((p) => {
280
390
  return p === "@emotion" || p === "@emotion/babel-plugin";
281
391
  });
282
- const define = {};
283
- if (opts.config.define) {
284
- for (const key of Object.keys(opts.config.define)) {
285
- define[key] = normalizeDefineValue(opts.config.define[key]);
286
- }
287
- }
288
- if (process.env.SOCKET_SERVER) {
289
- define["process.env.SOCKET_SERVER"] = normalizeDefineValue(
290
- process.env.SOCKET_SERVER
291
- );
292
- }
392
+ const define = getUtoopackDefine(opts);
293
393
  const {
294
394
  publicPath,
295
395
  runtimePublicPath,
@@ -335,14 +435,106 @@ async function getProdUtooPackConfig(opts) {
335
435
  define,
336
436
  nodePolyfill: true,
337
437
  mdx: !!mdx,
338
- externals: getNormalizedExternals(userExternals),
339
- ...getSvgModuleRules({ svgr, svgo, inlineLimit })
438
+ externals: getNormalizedExternals(userExternals)
340
439
  },
440
+ getExtraBabelModuleRules(opts),
441
+ getSvgModuleRules({ svgr, svgo, inlineLimit }),
341
442
  userUtoopackConfig
342
443
  )
343
444
  };
344
445
  return utooBundlerOpts;
345
446
  }
447
+ async function getSSRUtooPackConfig(opts) {
448
+ var _a;
449
+ const utooBundlerOpts = await getProdUtooPackConfig({
450
+ ...opts,
451
+ clean: false,
452
+ disableCopy: true
453
+ });
454
+ const entry = Object.entries(opts.entry)[0];
455
+ const entryName = (entry == null ? void 0 : entry[0]) || "umi.server";
456
+ const entryPath = entry == null ? void 0 : entry[1];
457
+ const filename = opts.useHash ? "[name].[contenthash:8].js" : (0, import_path.basename)(opts.serverBuildPath);
458
+ const ssrAssetsLoader = {
459
+ loader: require.resolve("./ssrAssetsLoader"),
460
+ options: {
461
+ cwd: opts.cwd
462
+ }
463
+ };
464
+ const ssrStylesLoader = {
465
+ loader: require.resolve("./ssrStylesLoader"),
466
+ options: {
467
+ cwd: opts.cwd
468
+ }
469
+ };
470
+ const ssrAssetRules = [
471
+ "*.png",
472
+ "*.jpg",
473
+ "*.jpeg",
474
+ "*.gif",
475
+ "*.webp",
476
+ "*.avif",
477
+ "*.ico",
478
+ "*.woff",
479
+ "*.woff2",
480
+ "*.ttf",
481
+ "*.eot",
482
+ "*.mp3",
483
+ "*.mp4"
484
+ ].reduce((memo, key) => {
485
+ memo[key] = {
486
+ loaders: [ssrAssetsLoader],
487
+ as: "*.js"
488
+ };
489
+ return memo;
490
+ }, {});
491
+ const ssrStyleRules = ["*.css", "*.less", "*.sass", "*.scss"].reduce(
492
+ (memo, key) => {
493
+ memo[key] = {
494
+ loaders: [ssrStylesLoader],
495
+ as: "*.js"
496
+ };
497
+ return memo;
498
+ },
499
+ {}
500
+ );
501
+ utooBundlerOpts.config = {
502
+ ...utooBundlerOpts.config,
503
+ entry: [
504
+ {
505
+ name: entryName,
506
+ import: entryPath,
507
+ library: {}
508
+ }
509
+ ],
510
+ output: {
511
+ ...utooBundlerOpts.config.output,
512
+ path: (0, import_path.dirname)(opts.serverBuildPath),
513
+ filename,
514
+ chunkFilename: filename,
515
+ clean: false,
516
+ copy: [],
517
+ publicPath: "/"
518
+ },
519
+ target: "node",
520
+ sourceMaps: false,
521
+ stats: true,
522
+ nodePolyfill: false,
523
+ module: {
524
+ ...utooBundlerOpts.config.module,
525
+ rules: {
526
+ ...(_a = utooBundlerOpts.config.module) == null ? void 0 : _a.rules,
527
+ ...ssrAssetRules,
528
+ ...ssrStyleRules
529
+ }
530
+ },
531
+ optimization: {
532
+ ...utooBundlerOpts.config.optimization,
533
+ minify: false
534
+ }
535
+ };
536
+ return utooBundlerOpts;
537
+ }
346
538
  async function getDevUtooPackConfig(opts) {
347
539
  var _a;
348
540
  let webpackConfig = await (0, import_bundler_webpack.getConfig)({
@@ -379,17 +571,7 @@ async function getDevUtooPackConfig(opts) {
379
571
  const emotion = extraBabelPlugins.some((p) => {
380
572
  return p === "@emotion" || p === "@emotion/babel-plugin";
381
573
  });
382
- const define = {};
383
- if (opts.config.define) {
384
- for (const key of Object.keys(opts.config.define)) {
385
- define[key] = normalizeDefineValue(opts.config.define[key]);
386
- }
387
- }
388
- if (process.env.SOCKET_SERVER) {
389
- define["process.env.SOCKET_SERVER"] = normalizeDefineValue(
390
- process.env.SOCKET_SERVER
391
- );
392
- }
574
+ const define = getUtoopackDefine(opts);
393
575
  const {
394
576
  publicPath,
395
577
  runtimePublicPath,
@@ -406,7 +588,7 @@ async function getDevUtooPackConfig(opts) {
406
588
  ...process.env.SOCKET_SERVER ? {
407
589
  processEnv: {
408
590
  ...utooBundlerOpts.processEnv || {},
409
- "process.env.SOCKET_SERVER": define["process.env.SOCKET_SERVER"]
591
+ "process.env.SOCKET_SERVER": process.env.SOCKET_SERVER
410
592
  }
411
593
  } : {},
412
594
  config: import_utils.lodash.merge(
@@ -441,8 +623,8 @@ async function getDevUtooPackConfig(opts) {
441
623
  emotion
442
624
  },
443
625
  define,
444
- // dev enable persistent cache by default
445
- persistentCaching: true,
626
+ // Windows persistent cache restore is currently unstable in utoopack dev.
627
+ persistentCaching: getDefaultPersistentCaching(),
446
628
  nodePolyfill: true,
447
629
  mdx: !!mdx,
448
630
  externals: getNormalizedExternals(userExternals),
@@ -451,9 +633,10 @@ async function getDevUtooPackConfig(opts) {
451
633
  react: {
452
634
  absoluteSourceFilename: true
453
635
  }
454
- } : {},
455
- ...getSvgModuleRules({ svgr, svgo, inlineLimit })
636
+ } : {}
456
637
  },
638
+ getExtraBabelModuleRules(opts),
639
+ getSvgModuleRules({ svgr, svgo, inlineLimit }),
457
640
  userUtoopackConfig
458
641
  ),
459
642
  watch: {
@@ -468,5 +651,6 @@ async function getDevUtooPackConfig(opts) {
468
651
  0 && (module.exports = {
469
652
  getDevUtooPackConfig,
470
653
  getProdUtooPackConfig,
654
+ getSSRUtooPackConfig,
471
655
  mergeExtraPostcssPlugins
472
656
  });
package/dist/index.d.ts CHANGED
@@ -4,4 +4,8 @@ export { findRootDir } from '@utoo/pack';
4
4
  export * from './config';
5
5
  export type { IUtoopackUserConfig } from './types';
6
6
  export declare function build(opts: IOpts): Promise<any>;
7
+ export declare function buildSSR(opts: IOpts & {
8
+ serverBuildPath: string;
9
+ useHash?: boolean;
10
+ }): Promise<any>;
7
11
  export declare function dev(opts: IDevOpts): Promise<any>;
package/dist/index.js CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
33
  build: () => build,
34
+ buildSSR: () => buildSSR,
34
35
  dev: () => dev,
35
36
  findRootDir: () => import_pack.findRootDir
36
37
  });
@@ -106,6 +107,44 @@ async function build(opts) {
106
107
  );
107
108
  return stats;
108
109
  }
110
+ async function buildSSR(opts) {
111
+ var _a;
112
+ const { cwd } = opts;
113
+ const buildStartTime = Date.now();
114
+ const { build: utooPackBuild, findRootDir: findRootDir2 } = require("@utoo/pack");
115
+ const rootDir = getUtoopackRootDir(cwd, opts.config.utoopack, findRootDir2);
116
+ const utooPackConfig = await (0, import_config.getSSRUtooPackConfig)({
117
+ ...opts,
118
+ rootDir
119
+ });
120
+ try {
121
+ await utooPackBuild(utooPackConfig, cwd, rootDir);
122
+ } catch (e) {
123
+ console.error(e.message);
124
+ const err = new Error("Build SSR with utoopack failed.");
125
+ err.stack = null;
126
+ throw err;
127
+ }
128
+ const statsPath = import_path.default.join(
129
+ ((_a = utooPackConfig.config.output) == null ? void 0 : _a.path) || "server",
130
+ "stats.json"
131
+ );
132
+ const stats = JSON.parse(import_fs.default.readFileSync(statsPath, "utf-8"));
133
+ stats.hasErrors = () => false;
134
+ stats.toJson = () => stats;
135
+ stats.toString = () => {
136
+ };
137
+ stats.compilation = {
138
+ ...stats,
139
+ assets: stats.assets.reduce(
140
+ (acc, cur) => Object.assign(acc, { [cur.name]: cur }),
141
+ {}
142
+ )
143
+ };
144
+ const time = Date.now() - buildStartTime;
145
+ stats.time = time;
146
+ return stats;
147
+ }
109
148
  async function dev(opts) {
110
149
  const { cwd, onDevCompileDone } = opts;
111
150
  if (!opts) {
@@ -269,6 +308,7 @@ async function dev(opts) {
269
308
  // Annotate the CommonJS export names for ESM import in node:
270
309
  0 && (module.exports = {
271
310
  build,
311
+ buildSSR,
272
312
  dev,
273
313
  findRootDir,
274
314
  ...require("./config")
@@ -0,0 +1 @@
1
+ export default function ssrAssetsLoader(this: any): string;
@@ -0,0 +1,35 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/ssrAssetsLoader.ts
20
+ var ssrAssetsLoader_exports = {};
21
+ __export(ssrAssetsLoader_exports, {
22
+ default: () => ssrAssetsLoader
23
+ });
24
+ module.exports = __toCommonJS(ssrAssetsLoader_exports);
25
+ var import_utils = require("@umijs/utils");
26
+ function ensureLastSlash(path) {
27
+ return path.endsWith("/") ? path : path + "/";
28
+ }
29
+ function ssrAssetsLoader() {
30
+ var _a;
31
+ const options = ((_a = this.getOptions) == null ? void 0 : _a.call(this)) || {};
32
+ const cwd = (0, import_utils.winPath)(options.cwd || this.rootContext || process.cwd());
33
+ const filename = (0, import_utils.winPath)(this.resourcePath).replace(ensureLastSlash(cwd), "");
34
+ return `export default global.g_getAssets(${JSON.stringify(filename)});`;
35
+ }
@@ -0,0 +1,2 @@
1
+ /// <reference types="node" />
2
+ export default function ssrStylesLoader(this: any, content: string | Buffer): string;
@@ -0,0 +1,54 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+
19
+ // src/ssrStylesLoader.ts
20
+ var ssrStylesLoader_exports = {};
21
+ __export(ssrStylesLoader_exports, {
22
+ default: () => ssrStylesLoader
23
+ });
24
+ module.exports = __toCommonJS(ssrStylesLoader_exports);
25
+ var import_utils = require("@umijs/utils");
26
+ function ensureLastSlash(path) {
27
+ return path.endsWith("/") ? path : path + "/";
28
+ }
29
+ function hashString(str) {
30
+ let hash = Buffer.from(str).toString("base64").replace(/=/g, "");
31
+ hash = hash.substring(hash.length - 5);
32
+ return hash;
33
+ }
34
+ function getClassNames(code) {
35
+ const classNames = /* @__PURE__ */ new Set();
36
+ const regexp = /\.([_a-zA-Z][\w-]*)/g;
37
+ let match;
38
+ while (match = regexp.exec(code)) {
39
+ classNames.add(match[1]);
40
+ }
41
+ return Array.from(classNames);
42
+ }
43
+ function ssrStylesLoader(content) {
44
+ var _a;
45
+ const options = ((_a = this.getOptions) == null ? void 0 : _a.call(this)) || {};
46
+ const cwd = (0, import_utils.winPath)(options.cwd || this.rootContext || process.cwd());
47
+ const filename = (0, import_utils.winPath)(this.resourcePath).replace(ensureLastSlash(cwd), "");
48
+ const code = Buffer.isBuffer(content) ? content.toString() : content;
49
+ const cssModuleObject = getClassNames(code).sort().reduce((memo, key) => {
50
+ memo[key] = `${key}___${hashString(`${filename}@${key}`)}`;
51
+ return memo;
52
+ }, {});
53
+ return `export default ${JSON.stringify(cssModuleObject)};`;
54
+ }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { IOpts as IConfigOpts } from '@umijs/bundler-webpack';
2
2
  import type { ConfigComplete } from '@utoo/pack';
3
3
  export declare type IUtoopackUserConfig = ConfigComplete & {
4
+ babelLoader?: boolean;
4
5
  root?: string;
5
6
  };
6
7
  export declare type IOpts = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/bundler-utoopack",
3
- "version": "4.6.51",
3
+ "version": "4.6.53",
4
4
  "description": "@umijs/bundler-utoopack",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,7 +8,7 @@
8
8
  "dist"
9
9
  ],
10
10
  "dependencies": {
11
- "@utoo/pack": "1.4.3",
11
+ "@utoo/pack": "1.4.4",
12
12
  "compression": "^1.7.4",
13
13
  "connect-history-api-fallback": "^2.0.0",
14
14
  "cors": "^2.8.5",
@@ -20,8 +20,8 @@
20
20
  "resolve-url-loader": "5.0.0",
21
21
  "sass": "1.54.0",
22
22
  "sass-loader": "13.2.0",
23
- "@umijs/bundler-utils": "4.6.51",
24
- "@umijs/bundler-webpack": "4.6.51"
23
+ "@umijs/bundler-utils": "4.6.53",
24
+ "@umijs/bundler-webpack": "4.6.53"
25
25
  },
26
26
  "devDependencies": {
27
27
  "father": "4.1.5"