@umijs/bundler-webpack 4.0.13 → 4.0.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.
@@ -36,7 +36,7 @@ async function addAssetRules(opts) {
36
36
  maxSize: inlineLimit
37
37
  }
38
38
  });
39
- const fallback = rule.oneOf("fallback").exclude.add(/^$/).add(/\.(js|mjs|jsx|ts|tsx)$/).add(/\.(css|less|sass|scss|stylus)$/).add(/\.html$/).add(/\.json$/);
39
+ const fallback = rule.oneOf("fallback").exclude.add(/^$/).add(/\.(js|mjs|cjs|jsx|ts|tsx)$/).add(/\.(css|less|sass|scss|stylus)$/).add(/\.html$/).add(/\.json$/);
40
40
  if (userConfig.mdx) {
41
41
  fallback.add(/\.mdx?$/);
42
42
  }
@@ -7,7 +7,7 @@ export interface IOpts {
7
7
  entry: Record<string, string>;
8
8
  extraBabelPresets?: any[];
9
9
  extraBabelPlugins?: any[];
10
- extraBabelIncludes?: string[];
10
+ extraBabelIncludes?: Array<string | RegExp>;
11
11
  extraEsbuildLoaderHandler?: any[];
12
12
  babelPreset?: any;
13
13
  chainWebpack?: Function;
@@ -103,10 +103,11 @@ async function getConfig(opts) {
103
103
  config.devtool(isDev ? userConfig.devtool === false ? false : userConfig.devtool || import_constants.DEFAULT_DEVTOOL : userConfig.devtool);
104
104
  const absOutputPath = (0, import_path.resolve)(opts.cwd, userConfig.outputPath || import_constants.DEFAULT_OUTPUT_PATH);
105
105
  const disableCompress = process.env.COMPRESS === "none";
106
- config.output.path(absOutputPath).filename(useHash ? `[name].[contenthash:8].js` : `[name].js`).chunkFilename(useHash ? `[name].[contenthash:8].async.js` : `[name].async.js`).publicPath(userConfig.publicPath || "auto").pathinfo(isDev || disableCompress).set("assetModuleFilename", `${applyOpts.staticPathPrefix}[name].[hash:8][ext]`);
106
+ config.output.path(absOutputPath).filename(useHash ? `[name].[contenthash:8].js` : `[name].js`).chunkFilename(useHash ? `[name].[contenthash:8].async.js` : `[name].async.js`).publicPath(userConfig.publicPath || "auto").pathinfo(isDev || disableCompress).set("assetModuleFilename", `${applyOpts.staticPathPrefix}[name].[hash:8][ext]`).set("hashFunction", "xxhash64");
107
107
  config.resolve.set("symlinks", true).modules.add("node_modules").end().alias.merge(userConfig.alias || {}).end().extensions.merge([
108
108
  ".wasm",
109
109
  ".mjs",
110
+ ".cjs",
110
111
  ".js",
111
112
  ".jsx",
112
113
  ".ts",
@@ -7,6 +7,6 @@ export interface Options extends DeadCodeParams {
7
7
  detectUnusedFiles: boolean;
8
8
  detectUnusedExport: boolean;
9
9
  }
10
- export declare const disabledFolders: string[];
10
+ export declare const ignores: string[];
11
11
  declare const detectDeadCode: (compilation: Compilation, options: Options) => void;
12
12
  export default detectDeadCode;
@@ -23,22 +23,37 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
23
23
  var detectDeadCode_exports = {};
24
24
  __export(detectDeadCode_exports, {
25
25
  default: () => detectDeadCode_default,
26
- disabledFolders: () => disabledFolders
26
+ ignores: () => ignores
27
27
  });
28
28
  module.exports = __toCommonJS(detectDeadCode_exports);
29
29
  var import_webpack = require("@umijs/bundler-webpack/compiled/webpack");
30
30
  var import_utils = require("@umijs/utils");
31
31
  var import_path = __toESM(require("path"));
32
- var disabledFolders = [
33
- "node_modules",
34
- ".umi",
35
- ".umi-production",
36
- "dist"
32
+ var ignores = [
33
+ "**/node_modules/**",
34
+ "**/.umi/**",
35
+ "**/.umi-production/**",
36
+ "**/.umi-test/**",
37
+ "coverage/**",
38
+ "dist/**",
39
+ "config/**",
40
+ "public/**",
41
+ "mock/**"
37
42
  ];
38
43
  var detectDeadCode = (compilation, options) => {
39
44
  const assets = getWebpackAssets(compilation);
40
45
  const compiledFilesDictionary = convertFilesToDict(assets);
41
- const includedFiles = getPattern(options).map((pattern) => import_utils.glob.sync(pattern)).flat();
46
+ const context = options.context;
47
+ if (!options.patterns.length) {
48
+ options.patterns = getDefaultSourcePattern({ cwd: context });
49
+ }
50
+ const includedFiles = options.patterns.map((pattern) => {
51
+ return import_utils.glob.sync(pattern, {
52
+ ignore: [...ignores, ...options.exclude],
53
+ cwd: context,
54
+ absolute: true
55
+ });
56
+ }).flat();
42
57
  const unusedFiles = options.detectUnusedFiles ? includedFiles.filter((file) => !compiledFilesDictionary[file]) : [];
43
58
  const unusedExportMap = options.detectUnusedExport ? getUnusedExportMap(convertFilesToDict(includedFiles), compilation) : {};
44
59
  logUnusedFiles(unusedFiles);
@@ -48,9 +63,6 @@ var detectDeadCode = (compilation, options) => {
48
63
  process.exit(2);
49
64
  }
50
65
  };
51
- var getPattern = (options) => {
52
- return options.patterns.map((pattern) => import_path.default.resolve(options.context || "", pattern)).concat(options.exclude.map((pattern) => import_path.default.resolve(options.context || "", `!${pattern}`))).map(convertToUnixPath);
53
- };
54
66
  var getUnusedExportMap = (includedFileMap, compilation) => {
55
67
  const unusedExportMap = {};
56
68
  compilation.chunks.forEach((chunk) => {
@@ -64,7 +76,7 @@ var outputUnusedExportMap = (compilation, chunk, module2, includedFileMap, unuse
64
76
  if (!(module2 instanceof import_webpack.NormalModule) || !module2.resource) {
65
77
  return;
66
78
  }
67
- const path2 = convertToUnixPath(module2.resource);
79
+ const path2 = (0, import_utils.winPath)(module2.resource);
68
80
  if (!/^((?!(node_modules)).)*$/.test(path2))
69
81
  return;
70
82
  const providedExports = compilation.chunkGraph.moduleGraph.getProvidedExports(module2);
@@ -111,8 +123,8 @@ var getWebpackAssets = (compilation) => {
111
123
  return assets;
112
124
  };
113
125
  var convertFilesToDict = (assets) => {
114
- return assets.filter((file) => Boolean(file) && disabledFolders.every((disabledPath) => !file.includes(disabledPath))).reduce((fileDictionary, file) => {
115
- const unixFile = convertToUnixPath(file);
126
+ return assets.filter((path2) => !/(node_modules|(\.umi))/.test(path2) && Boolean(path2)).reduce((fileDictionary, file) => {
127
+ const unixFile = (0, import_utils.winPath)(file);
116
128
  fileDictionary[unixFile] = true;
117
129
  return fileDictionary;
118
130
  }, {});
@@ -124,9 +136,22 @@ var logUnusedFiles = (unusedFiles) => {
124
136
  console.log(import_utils.chalk.yellow.bold("\nWarning:"), import_utils.chalk.yellow(`There are ${unusedFiles.length} unused files:`), ...unusedFiles.map((file, index) => `
125
137
  ${index + 1}. ${import_utils.chalk.yellow(file)}`), import_utils.chalk.red.bold("\nPlease be careful if you want to remove them (\xAC\xBA-\xB0)\xAC.\n"));
126
138
  };
127
- var convertToUnixPath = (path2) => path2.replace(/\\+/g, "/");
139
+ function isDirExist(p) {
140
+ return import_utils.fsExtra.existsSync(p) && import_utils.fsExtra.statSync(p).isDirectory();
141
+ }
142
+ function getDefaultSourcePattern(opts) {
143
+ const { cwd } = opts;
144
+ const srcPath = import_path.default.join(cwd, "src");
145
+ if (isDirExist(srcPath)) {
146
+ return ["src/**/*"];
147
+ }
148
+ const dirs = import_utils.fsExtra.readdirSync(cwd).filter((p) => {
149
+ return !p.startsWith(".") && isDirExist(p);
150
+ });
151
+ return dirs.map((dir) => `${dir}/**/*`);
152
+ }
128
153
  var detectDeadCode_default = detectDeadCode;
129
154
  // Annotate the CommonJS export names for ESM import in node:
130
155
  0 && (module.exports = {
131
- disabledFolders
156
+ ignores
132
157
  });
@@ -45,7 +45,7 @@ module.exports = __toCommonJS(detectDeadCodePlugin_exports);
45
45
  var import_types = require("../types");
46
46
  var import_detectDeadCode = __toESM(require("./detectDeadCode"));
47
47
  var defaultOptions = {
48
- patterns: [`!(${import_detectDeadCode.disabledFolders.join("|")})/**/*.*`],
48
+ patterns: [],
49
49
  exclude: [],
50
50
  failOnHint: false,
51
51
  detectUnusedFiles: true,
@@ -7,7 +7,7 @@ interface IOpts {
7
7
  env: Env;
8
8
  extraBabelPlugins: any[];
9
9
  extraBabelPresets: any[];
10
- extraBabelIncludes: string[];
10
+ extraBabelIncludes: Array<string | RegExp>;
11
11
  extraEsbuildLoaderHandler: any[];
12
12
  babelPreset: any;
13
13
  name?: string;
@@ -39,13 +39,16 @@ async function addJavaScriptRules(opts) {
39
39
  const useFastRefresh = isDev && userConfig.fastRefresh !== false && name !== import_constants.MFSU_NAME;
40
40
  const depPkgs = Object.assign({}, (0, import_depMatch.es5ImcompatibleVersionsToPkg)());
41
41
  const srcRules = [
42
- config.module.rule("src").test(/\.(js|mjs)$/).include.add([
42
+ config.module.rule("src").test(/\.(js|mjs|cjs)$/).include.add([
43
43
  cwd,
44
44
  ...process.env.APP_ROOT ? [process.cwd()] : []
45
45
  ]).end().exclude.add(/node_modules/).end(),
46
46
  config.module.rule("jsx-ts-tsx").test(/\.(jsx|ts|tsx)$/),
47
- config.module.rule("extra-src").test(/\.(js|mjs)$/).include.add([
47
+ config.module.rule("extra-src").test(/\.(js|mjs|cjs)$/).include.add([
48
48
  ...opts.extraBabelIncludes.map((p) => {
49
+ if (import_utils.lodash.isRegExp(p)) {
50
+ return p;
51
+ }
49
52
  if ((0, import_path.isAbsolute)(p)) {
50
53
  return p;
51
54
  }
@@ -77,7 +80,7 @@ async function addJavaScriptRules(opts) {
77
80
  srcRules.push(config.module.rule("markdown").test(/\.mdx?$/));
78
81
  }
79
82
  const depRules = [
80
- config.module.rule("dep").test(/\.(js|mjs)$/).include.add(/node_modules/).end().exclude.add((path) => {
83
+ config.module.rule("dep").test(/\.(js|mjs|cjs)$/).include.add(/node_modules/).end().exclude.add((path) => {
81
84
  try {
82
85
  return (0, import_depMatch.isMatch)({ path, pkgs: depPkgs });
83
86
  } catch (e) {
package/dist/dev.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /// <reference types="node" />
2
+ import type { Worker } from 'worker_threads';
1
3
  import { IOpts as IConfigOpts } from './config/config';
2
4
  import { IConfig } from './types';
3
5
  declare type IOpts = {
@@ -8,6 +10,7 @@ declare type IOpts = {
8
10
  onMFSUProgress?: Function;
9
11
  port?: number;
10
12
  host?: string;
13
+ ip?: string;
11
14
  babelPreset?: any;
12
15
  chainWebpack?: Function;
13
16
  modifyWebpackConfig?: Function;
@@ -21,7 +24,9 @@ declare type IOpts = {
21
24
  entry: Record<string, string>;
22
25
  mfsuStrategy?: 'eager' | 'normal';
23
26
  mfsuInclude?: string[];
27
+ mfsuServerBase?: string;
24
28
  srcCodeCache?: any;
29
+ startBuildWorker?: (deps: any[]) => Worker;
25
30
  } & Pick<IConfigOpts, 'cache' | 'pkg'>;
26
31
  export declare function stripUndefined(obj: any): any;
27
32
  export declare function dev(opts: IOpts): Promise<void>;
package/dist/dev.js CHANGED
@@ -65,10 +65,6 @@ async function dev(opts) {
65
65
  const cacheDirectoryPath = (0, import_path.resolve)(opts.rootDir || opts.cwd, opts.config.cacheDirectoryPath || "node_modules/.cache");
66
66
  const enableMFSU = opts.config.mfsu !== false;
67
67
  let mfsu = null;
68
- let devHost = "localhost";
69
- if (opts.host && opts.host !== "0.0.0.0") {
70
- devHost = opts.host;
71
- }
72
68
  if (enableMFSU) {
73
69
  if (opts.config.srcTranspiler === import_types.Transpiler.swc) {
74
70
  import_utils.logger.warn(`Swc currently not supported for use with mfsu, recommended you use srcTranspiler: 'esbuild' in dev.`);
@@ -101,7 +97,8 @@ async function dev(opts) {
101
97
  publicPath: opts.config.publicPath
102
98
  });
103
99
  },
104
- serverBase: `${opts.config.https ? "https" : "http"}://${devHost}:${opts.port || 8e3}`
100
+ serverBase: opts.mfsuServerBase,
101
+ startBuildWorker: opts.startBuildWorker
105
102
  });
106
103
  }
107
104
  const webpackConfig = await (0, import_config.getConfig)({
@@ -174,7 +171,8 @@ async function dev(opts) {
174
171
  ...opts.beforeMiddlewares || []
175
172
  ],
176
173
  port: opts.port,
177
- host: devHost,
174
+ host: opts.host,
175
+ ip: opts.ip,
178
176
  afterMiddlewares: [...opts.afterMiddlewares || []],
179
177
  onDevCompileDone: opts.onDevCompileDone,
180
178
  onProgress: opts.onProgress
package/dist/schema.js CHANGED
@@ -73,7 +73,7 @@ function getSchemas() {
73
73
  devtool: (Joi) => Joi.alternatives().try(Joi.string().regex(DEVTOOL_REGEX), Joi.boolean()),
74
74
  esm: (Joi) => Joi.object(),
75
75
  externals: (Joi) => Joi.alternatives().try(Joi.object(), Joi.string(), Joi.func()),
76
- extraBabelIncludes: (Joi) => Joi.array().items(Joi.string()),
76
+ extraBabelIncludes: (Joi) => Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.object().instance(RegExp))),
77
77
  extraBabelPlugins: (Joi) => Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.array())),
78
78
  extraBabelPresets: (Joi) => Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.array())),
79
79
  extraPostCSSPlugins: (Joi) => Joi.array(),
@@ -6,6 +6,7 @@ interface IOpts {
6
6
  cwd: string;
7
7
  port?: number;
8
8
  host?: string;
9
+ ip?: string;
9
10
  webpackConfig: Configuration;
10
11
  userConfig: IConfig;
11
12
  beforeMiddlewares?: any[];
@@ -58,6 +58,7 @@ async function createServer(opts) {
58
58
  const { webpackConfig, userConfig } = opts;
59
59
  const { proxy } = userConfig;
60
60
  const app = (0, import_express.default)();
61
+ let ws;
61
62
  app.use((0, import_cors.default)({
62
63
  origin: true,
63
64
  methods: ["GET", "HEAD", "PUT", "POST", "PATCH", "DELETE", "OPTIONS"],
@@ -148,7 +149,8 @@ async function createServer(opts) {
148
149
  });
149
150
  }
150
151
  function sendMessage(type, data, sender) {
151
- (sender || ws).send(JSON.stringify({ type, data }));
152
+ var _a;
153
+ (_a = sender || ws) == null ? void 0 : _a.send(JSON.stringify({ type, data }));
152
154
  }
153
155
  if (proxy) {
154
156
  const proxyArr = Array.isArray(proxy) ? proxy : proxy.target ? [proxy] : Object.keys(proxy).map((key) => {
@@ -167,7 +169,7 @@ async function createServer(opts) {
167
169
  if (proxyReq.getHeader("origin")) {
168
170
  proxyReq.setHeader("origin", ((_a = new URL(proxy2.target)) == null ? void 0 : _a.href) || "");
169
171
  }
170
- (_b = proxy2.onProxyReq) == null ? void 0 : _b.call(proxy2, proxyReq, req, res);
172
+ (_b = proxy2.onProxyReq) == null ? void 0 : _b.call(proxy2, proxyReq, req, res, proxy2);
171
173
  },
172
174
  onProxyRes(proxyRes, req, res) {
173
175
  var _a, _b;
@@ -209,11 +211,26 @@ async function createServer(opts) {
209
211
  next();
210
212
  }
211
213
  });
212
- const server = userConfig.https ? await (0, import_bundler_utils.createHttpsServer)(app, userConfig.https) : import_http.default.createServer(app);
214
+ let server;
215
+ if (userConfig.https) {
216
+ const httpsOpts = userConfig.https;
217
+ if (!httpsOpts.hosts) {
218
+ httpsOpts.hosts = import_utils.lodash.uniq([
219
+ ...httpsOpts.hosts || [],
220
+ "127.0.0.1",
221
+ "localhost",
222
+ opts.ip,
223
+ opts.host !== "0.0.0.0" && opts.host
224
+ ].filter(Boolean));
225
+ }
226
+ server = await (0, import_bundler_utils.createHttpsServer)(app, httpsOpts);
227
+ } else {
228
+ server = import_http.default.createServer(app);
229
+ }
213
230
  if (!server) {
214
231
  return null;
215
232
  }
216
- const ws = (0, import_ws.createWebSocketServer)(server);
233
+ ws = (0, import_ws.createWebSocketServer)(server);
217
234
  ws.wss.on("connection", (socket) => {
218
235
  if (stats) {
219
236
  sendStats(getStats(stats), false, socket);
package/dist/types.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Config as SwcConfig } from '@swc/core';
2
2
  import type { HttpsServerOptions } from '@umijs/bundler-utils';
3
- import type { Options as ProxyOptions } from '../compiled/http-proxy-middleware';
3
+ import type { Options as HPMOptions } from '../compiled/http-proxy-middleware';
4
4
  import { Configuration } from '../compiled/webpack';
5
5
  import Config from '../compiled/webpack-5-chain';
6
6
  export declare enum Env {
@@ -33,7 +33,9 @@ export interface ICopy {
33
33
  declare type WebpackConfig = Required<Configuration>;
34
34
  declare type IBabelPlugin = Function | string | [string, {
35
35
  [key: string]: any;
36
- }];
36
+ }] | [string, {
37
+ [key: string]: any;
38
+ }, string];
37
39
  export interface DeadCodeParams {
38
40
  patterns?: string[];
39
41
  exclude?: string[];
@@ -42,6 +44,12 @@ export interface DeadCodeParams {
42
44
  detectUnusedExport?: boolean;
43
45
  context?: string;
44
46
  }
47
+ declare type HPMFnArgs = Parameters<NonNullable<HPMOptions['onProxyReq']>>;
48
+ export interface ProxyOptions extends HPMOptions {
49
+ target?: string;
50
+ context?: string | string[];
51
+ bypass?: (...args: [HPMFnArgs[1], HPMFnArgs[2], HPMFnArgs[3]]) => string | boolean | null | void;
52
+ }
45
53
  export interface IConfig {
46
54
  alias?: Record<string, string>;
47
55
  autoCSSModules?: boolean;
@@ -71,7 +79,7 @@ export interface IConfig {
71
79
  };
72
80
  extraBabelPlugins?: IBabelPlugin[];
73
81
  extraBabelPresets?: IBabelPlugin[];
74
- extraBabelIncludes?: string[];
82
+ extraBabelIncludes?: Array<string | RegExp>;
75
83
  extraPostCSSPlugins?: any[];
76
84
  hash?: boolean;
77
85
  ignoreMomentLocale?: boolean;
@@ -88,7 +96,7 @@ export interface IConfig {
88
96
  };
89
97
  proxy?: {
90
98
  [key: string]: ProxyOptions;
91
- };
99
+ } | ProxyOptions[];
92
100
  publicPath?: string;
93
101
  purgeCSS?: {
94
102
  [key: string]: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@umijs/bundler-webpack",
3
- "version": "4.0.13",
3
+ "version": "4.0.16",
4
4
  "description": "@umijs/bundler-webpack",
5
5
  "homepage": "https://github.com/umijs/umi/tree/master/packages/bundler-webpack#readme",
6
6
  "bugs": "https://github.com/umijs/umi/issues",
@@ -34,11 +34,11 @@
34
34
  "@svgr/plugin-jsx": "^6.2.1",
35
35
  "@svgr/plugin-svgo": "^6.2.0",
36
36
  "@types/hapi__joi": "17.1.8",
37
- "@umijs/babel-preset-umi": "4.0.13",
38
- "@umijs/bundler-utils": "4.0.13",
37
+ "@umijs/babel-preset-umi": "4.0.16",
38
+ "@umijs/bundler-utils": "4.0.16",
39
39
  "@umijs/case-sensitive-paths-webpack-plugin": "^1.0.1",
40
- "@umijs/mfsu": "4.0.13",
41
- "@umijs/utils": "4.0.13",
40
+ "@umijs/mfsu": "4.0.16",
41
+ "@umijs/utils": "4.0.16",
42
42
  "cors": "^2.8.5",
43
43
  "css-loader": "6.7.1",
44
44
  "es5-imcompatible-versions": "^0.1.73",