@umijs/bundler-webpack 4.0.0-rc.1 → 4.0.0-rc.12

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.
Files changed (121) hide show
  1. package/client/client/client.js +57 -37
  2. package/client/constants.js +9 -0
  3. package/compiled/autoprefixer/browserslist/index.d.ts +6 -0
  4. package/compiled/autoprefixer/index.js +3 -3
  5. package/compiled/autoprefixer/postcss/lib/at-rule.d.ts +1 -1
  6. package/compiled/autoprefixer/postcss/lib/comment.d.ts +1 -1
  7. package/compiled/autoprefixer/postcss/lib/declaration.d.ts +2 -2
  8. package/compiled/autoprefixer/postcss/lib/node.d.ts +2 -2
  9. package/compiled/autoprefixer/postcss/lib/rule.d.ts +1 -1
  10. package/compiled/autoprefixer/source-map-js/source-map.d.ts +99 -82
  11. package/compiled/babel-loader/index.js +2 -2
  12. package/compiled/copy-webpack-plugin/939.index.js +1171 -0
  13. package/compiled/copy-webpack-plugin/index.js +16 -10
  14. package/compiled/copy-webpack-plugin/package.json +1 -1
  15. package/compiled/css-minimizer-webpack-plugin/index.js +8 -2
  16. package/compiled/css-minimizer-webpack-plugin/minify.js +25 -11
  17. package/compiled/css-minimizer-webpack-plugin/package.json +1 -1
  18. package/compiled/css-minimizer-webpack-plugin/utils.js +225 -28
  19. package/compiled/cssnano/index.js +12 -11
  20. package/compiled/cssnano/package.json +1 -1
  21. package/compiled/express.d.ts +2 -0
  22. package/compiled/fork-ts-checker-webpack-plugin/index.js +8 -15
  23. package/compiled/http-proxy-middleware/dist/types.d.ts +5 -5
  24. package/compiled/http-proxy-middleware/http-proxy/index.d.ts +1 -1
  25. package/compiled/http-proxy-middleware/index.js +10 -10
  26. package/compiled/mini-css-extract-plugin/hmr/hotModuleReplacement.js +60 -8
  27. package/compiled/mini-css-extract-plugin/hmr/normalize-url.js +13 -1
  28. package/compiled/mini-css-extract-plugin/index.js +4523 -4036
  29. package/compiled/mini-css-extract-plugin/loader.js +179 -54
  30. package/compiled/mini-css-extract-plugin/package.json +1 -1
  31. package/compiled/mini-css-extract-plugin/utils.js +79 -23
  32. package/compiled/react-refresh/LICENSE +21 -0
  33. package/compiled/react-refresh/index.js +9 -7
  34. package/compiled/react-refresh/package.json +1 -0
  35. package/compiled/sass-loader/index.js +1 -1
  36. package/compiled/terser/index.js +1 -1
  37. package/compiled/terser-webpack-plugin/index.js +296 -297
  38. package/compiled/terser-webpack-plugin/minify.js +4 -2
  39. package/compiled/terser-webpack-plugin/package.json +1 -1
  40. package/compiled/terser-webpack-plugin/types/index.d.ts +180 -146
  41. package/compiled/terser-webpack-plugin/types/minify.d.ts +17 -0
  42. package/compiled/terser-webpack-plugin/types/utils.d.ts +1 -3
  43. package/compiled/terser-webpack-plugin/utils.js +9 -12
  44. package/compiled/webpack/HotModuleReplacement.runtime.js +29 -14
  45. package/compiled/webpack/JavascriptHotModuleReplacement.runtime.js +4 -3
  46. package/compiled/webpack/index.js +11589 -4372
  47. package/compiled/webpack-dev-middleware/index.js +7 -7
  48. package/compiled/webpack-dev-middleware/package.json +1 -1
  49. package/compiled/webpack-manifest-plugin/index.js +1 -1
  50. package/compiled/webpack-sources/index.js +1 -1
  51. package/compiled/ws/index.d.ts +1 -2
  52. package/compiled/ws/index.js +1 -1
  53. package/dist/build.d.ts +2 -1
  54. package/dist/build.js +1 -1
  55. package/dist/client/client.js +15 -4
  56. package/dist/config/compressPlugin.js +15 -1
  57. package/dist/config/config.js +7 -3
  58. package/dist/config/cssRules.js +1 -1
  59. package/dist/config/detectDeadCode.d.ts +12 -0
  60. package/dist/config/detectDeadCode.js +120 -0
  61. package/dist/config/detectDeadCodePlugin.d.ts +9 -0
  62. package/dist/config/detectDeadCodePlugin.js +75 -0
  63. package/dist/config/javaScriptRules.js +7 -12
  64. package/dist/config/nodePolyfill.js +1 -1
  65. package/dist/config/nodePrefixPlugin.d.ts +11 -0
  66. package/dist/config/nodePrefixPlugin.js +25 -0
  67. package/dist/constants.d.ts +4 -0
  68. package/dist/constants.js +10 -1
  69. package/dist/dev.d.ts +4 -0
  70. package/dist/dev.js +27 -8
  71. package/dist/index.d.ts +4 -1
  72. package/dist/index.js +5 -1
  73. package/dist/loader/swc.js +14 -18
  74. package/dist/plugins/ESBuildCSSMinifyPlugin.js +1 -3
  75. package/dist/plugins/ParcelCSSMinifyPlugin.d.ts +10 -0
  76. package/dist/plugins/ParcelCSSMinifyPlugin.js +75 -0
  77. package/dist/plugins/ProgressPlugin.js +2 -2
  78. package/dist/plugins/RuntimePublicPathPlugin.js +1 -1
  79. package/dist/requireHook.js +1 -1
  80. package/dist/schema.js +10 -6
  81. package/dist/server/https.d.ts +5 -0
  82. package/dist/server/https.js +73 -0
  83. package/dist/server/server.d.ts +2 -1
  84. package/dist/server/server.js +48 -11
  85. package/dist/server/ws.d.ts +3 -2
  86. package/dist/swcPlugins/autoCSSModules.d.ts +7 -2
  87. package/dist/swcPlugins/autoCSSModules.js +14 -17
  88. package/dist/swcPlugins/changeImportFromString.d.ts +2 -0
  89. package/dist/swcPlugins/changeImportFromString.js +10 -0
  90. package/dist/swcPlugins/lockCoreJS.d.ts +1 -1
  91. package/dist/swcPlugins/lockCoreJS.js +3 -2
  92. package/dist/types.d.ts +16 -12
  93. package/dist/types.js +1 -0
  94. package/dist/utils/depMatch.js +1 -1
  95. package/dist/utils/getEsBuildTarget.d.ts +5 -0
  96. package/dist/utils/getEsBuildTarget.js +12 -0
  97. package/package.json +40 -42
  98. package/compiled/css-loader/LICENSE +0 -20
  99. package/compiled/css-loader/api.js +0 -102
  100. package/compiled/css-loader/getUrl.js +0 -29
  101. package/compiled/css-loader/index.js +0 -2
  102. package/compiled/css-loader/noSourceMaps.js +0 -5
  103. package/compiled/css-loader/package.json +0 -1
  104. package/compiled/css-loader/sourceMaps.js +0 -22
  105. package/compiled/express/LICENSE +0 -24
  106. package/compiled/express/body-parser/index.d.ts +0 -104
  107. package/compiled/express/connect/index.d.ts +0 -93
  108. package/compiled/express/express-serve-static-core/index.d.ts +0 -1252
  109. package/compiled/express/index.d.ts +0 -133
  110. package/compiled/express/index.js +0 -338
  111. package/compiled/express/mime/index.d.ts +0 -35
  112. package/compiled/express/package.json +0 -1
  113. package/compiled/express/qs/index.d.ts +0 -62
  114. package/compiled/express/range-parser/index.d.ts +0 -35
  115. package/compiled/express/serve-static/index.d.ts +0 -108
  116. package/compiled/less/index.js +0 -31
  117. package/compiled/less/package.json +0 -1
  118. package/dist/esbuildHandler/autoCssModules.d.ts +0 -2
  119. package/dist/esbuildHandler/autoCssModules.js +0 -23
  120. package/dist/loader/esbuild.d.ts +0 -5
  121. package/dist/loader/esbuild.js +0 -53
@@ -0,0 +1,75 @@
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
+ exports.ParcelCSSMinifyPlugin = void 0;
13
+ const utils_1 = require("@umijs/utils");
14
+ const buffer_1 = require("buffer");
15
+ const path_1 = require("path");
16
+ const webpack_sources_1 = require("../../compiled/webpack-sources");
17
+ const pkgPath = (0, path_1.join)(__dirname, '../../package.json');
18
+ const pkg = require(pkgPath);
19
+ const PLUGIN_NAME = 'parcel-css-minify-plugin';
20
+ const CSS_FILE_REG = /\.css(?:\?.*)?$/i;
21
+ class ParcelCSSMinifyPlugin {
22
+ constructor(opts = {}) {
23
+ this.options = opts;
24
+ }
25
+ apply(compiler) {
26
+ const meta = JSON.stringify({
27
+ name: pkg.name,
28
+ version: pkg.version,
29
+ options: this.options,
30
+ });
31
+ compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
32
+ compilation.hooks.chunkHash.tap(PLUGIN_NAME, (_, hash) => hash.update(meta));
33
+ compilation.hooks.processAssets.tapPromise({
34
+ name: PLUGIN_NAME,
35
+ // @ts-ignore
36
+ stage: compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
37
+ additionalAssets: true,
38
+ }, () => __awaiter(this, void 0, void 0, function* () { return yield this.transformAssets(compilation); }));
39
+ compilation.hooks.statsPrinter.tap(PLUGIN_NAME, (statsPrinter) => {
40
+ statsPrinter.hooks.print
41
+ .for('asset.info.minimized')
42
+ // @ts-ignore
43
+ .tap(PLUGIN_NAME, (minimized, { green, formatFlag }) => {
44
+ // @ts-ignore
45
+ return minimized ? green(formatFlag('minimized')) : undefined;
46
+ });
47
+ });
48
+ });
49
+ }
50
+ transformAssets(compilation) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const { options: { devtool }, } = compilation.compiler;
53
+ const sourcemap = this.options.sourceMap === undefined
54
+ ? (devtool && devtool.includes('source-map'))
55
+ : this.options.sourceMap;
56
+ const assets = compilation.getAssets().filter((asset) => {
57
+ return !asset.info.minimized && CSS_FILE_REG.test(asset.name);
58
+ });
59
+ yield Promise.all(assets.map((asset) => __awaiter(this, void 0, void 0, function* () {
60
+ const { source, map } = asset.source.sourceAndMap();
61
+ const sourceAsString = source.toString();
62
+ const code = typeof source === 'string' ? buffer_1.Buffer.from(source) : source;
63
+ const { transform } = (0, utils_1.importLazy)('@parcel/css');
64
+ const result = yield transform(Object.assign({ filename: asset.name, code, minify: true, sourceMap: sourcemap }, this.options));
65
+ const codeString = result.code.toString();
66
+ compilation.updateAsset(asset.name,
67
+ // @ts-ignore
68
+ sourcemap
69
+ ? new webpack_sources_1.SourceMapSource(codeString, asset.name, JSON.parse(result.map.toString()), sourceAsString, map, true)
70
+ : new webpack_sources_1.RawSource(codeString), Object.assign(Object.assign({}, asset.info), { minimized: true }));
71
+ })));
72
+ });
73
+ }
74
+ }
75
+ exports.ParcelCSSMinifyPlugin = ParcelCSSMinifyPlugin;
@@ -13,7 +13,7 @@ class UmiProgressPlugin extends webpack_1.ProgressPlugin {
13
13
  }
14
14
  apply(compiler) {
15
15
  compiler.hooks.invalid.tap(PLUGIN_NAME, () => {
16
- utils_1.logger.wait('compiling...');
16
+ utils_1.logger.wait('Compiling...');
17
17
  });
18
18
  compiler.hooks.done.tap(PLUGIN_NAME, (stats) => {
19
19
  const { errors, warnings } = stats.toJson({
@@ -33,7 +33,7 @@ class UmiProgressPlugin extends webpack_1.ProgressPlugin {
33
33
  }
34
34
  else {
35
35
  const prefix = this.options.name ? `${this.options.name} ` : '';
36
- utils_1.logger.event(`${prefix}compiled successfully in ${stats.endTime - stats.startTime} ms (${stats.compilation.modules.size} modules)`);
36
+ utils_1.logger.event(`${prefix}Compiled successfully in ${stats.endTime - stats.startTime} ms (${stats.compilation.modules.size} modules)`);
37
37
  }
38
38
  });
39
39
  }
@@ -11,7 +11,7 @@ class RuntimePublicPathPlugin {
11
11
  // https://github.com/webpack/webpack/blob/master/lib/runtime/PublicPathRuntimeModule.js
12
12
  if (module.constructor.name === 'PublicPathRuntimeModule') {
13
13
  // @ts-ignore
14
- module._cachedGeneratedCode = `__webpack_require__.p = window.publicPath;`;
14
+ module._cachedGeneratedCode = `__webpack_require__.p = (globalThis || window).publicPath;`;
15
15
  }
16
16
  });
17
17
  });
@@ -17,7 +17,7 @@ const hookPropertyMap = new Map([
17
17
  ['webpack/lib/webpack.js', '@umijs/bundler-webpack/compiled/webpack'],
18
18
  ]);
19
19
  deepImports_json_1.default.forEach((item) => {
20
- const name = item.split('/').unshift();
20
+ const name = item.split('/').pop();
21
21
  hookPropertyMap.set(item, `@umijs/bundler-webpack/compiled/webpack/${name}`);
22
22
  hookPropertyMap.set(`${item}.js`, `@umijs/bundler-webpack/compiled/webpack/${name}`);
23
23
  });
package/dist/schema.js CHANGED
@@ -32,18 +32,21 @@ function getSchemas() {
32
32
  }), Joi.string())),
33
33
  cssLoader: (Joi) => Joi.object(),
34
34
  cssLoaderModules: (Joi) => Joi.object(),
35
- cssMinifier: (Joi) => Joi.string().valid(types_1.CSSMinifier.cssnano, types_1.CSSMinifier.esbuild, types_1.CSSMinifier.none),
35
+ cssMinifier: (Joi) => Joi.string().valid(types_1.CSSMinifier.cssnano, types_1.CSSMinifier.esbuild, types_1.CSSMinifier.parcelCSS, types_1.CSSMinifier.none),
36
36
  cssMinifierOptions: (Joi) => Joi.object(),
37
+ deadCode: (Joi) => Joi.object(),
37
38
  define: (Joi) => Joi.object(),
38
39
  depTranspiler: (Joi) => Joi.string().valid(types_1.Transpiler.babel, types_1.Transpiler.esbuild, types_1.Transpiler.swc, types_1.Transpiler.none),
39
40
  devtool: (Joi) => Joi.alternatives().try(Joi.string().regex(DEVTOOL_REGEX), Joi.boolean()),
41
+ esm: (Joi) => Joi.object(),
40
42
  externals: (Joi) => Joi.alternatives().try(Joi.object(), Joi.string(), Joi.func()),
41
- extraBabelPlugins: (Joi) => Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.object()))),
42
- extraBabelPresets: (Joi) => Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.object()))),
43
+ extraBabelPlugins: (Joi) => Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.array())),
44
+ extraBabelPresets: (Joi) => Joi.array().items(Joi.alternatives().try(Joi.string(), Joi.array())),
43
45
  extraPostCSSPlugins: (Joi) => Joi.array(),
44
46
  fastRefresh: (Joi) => Joi.boolean(),
45
47
  forkTSChecker: (Joi) => Joi.object(),
46
48
  hash: (Joi) => Joi.boolean(),
49
+ https: (Joi) => Joi.object(),
47
50
  ignoreMomentLocale: (Joi) => Joi.boolean(),
48
51
  inlineLimit: (Joi) => Joi.number(),
49
52
  jsMinifier: (Joi) => Joi.string().valid(types_1.JSMinifier.esbuild, types_1.JSMinifier.swc, types_1.JSMinifier.terser, types_1.JSMinifier.uglifyJs, types_1.JSMinifier.none),
@@ -55,6 +58,8 @@ function getSchemas() {
55
58
  loaderOptions: Joi.object(),
56
59
  }),
57
60
  mfsu: (Joi) => Joi.alternatives(Joi.object({
61
+ cacheDirectory: Joi.string(),
62
+ chainWebpack: Joi.function(),
58
63
  esbuild: Joi.boolean(),
59
64
  mfName: Joi.string(),
60
65
  }), Joi.boolean()),
@@ -67,12 +72,11 @@ function getSchemas() {
67
72
  sassLoader: (Joi) => Joi.object(),
68
73
  srcTranspiler: (Joi) => Joi.string().valid(types_1.Transpiler.babel, types_1.Transpiler.esbuild, types_1.Transpiler.swc, types_1.Transpiler.none),
69
74
  styleLoader: (Joi) => Joi.object(),
70
- svgr: (Joi) => Joi.object(),
71
75
  svgo: (Joi) => Joi.alternatives().try(Joi.object(), Joi.boolean()),
76
+ svgr: (Joi) => Joi.object(),
72
77
  targets: (Joi) => Joi.object(),
73
- writeToDisk: (Joi) => Joi.boolean(),
74
- esm: (Joi) => Joi.object(),
75
78
  theme: (Joi) => Joi.object(),
79
+ writeToDisk: (Joi) => Joi.boolean(),
76
80
  };
77
81
  }
78
82
  exports.getSchemas = getSchemas;
@@ -0,0 +1,5 @@
1
+ /// <reference types="node" />
2
+ import { RequestListener } from 'http';
3
+ import https from 'https';
4
+ import { HttpsParams } from '../types';
5
+ export declare function createHttpsServer(app: RequestListener, httpsConfig: HttpsParams): Promise<https.Server>;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.createHttpsServer = void 0;
16
+ const utils_1 = require("@umijs/utils");
17
+ const fs_1 = require("fs");
18
+ const https_1 = __importDefault(require("https"));
19
+ const path_1 = require("path");
20
+ const defaultHttpsHosts = ['localhost', '127.0.0.1'];
21
+ function createHttpsServer(app, httpsConfig) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ utils_1.logger.wait('[HTTPS] Starting service in https mode...');
24
+ // Check if mkcert is installed
25
+ try {
26
+ yield utils_1.execa.execa('mkcert', ['--version']);
27
+ }
28
+ catch (e) {
29
+ utils_1.logger.error('[HTTPS] The mkcert has not been installed.');
30
+ utils_1.logger.info('[HTTPS] Please follow the guide to install manually.');
31
+ switch (process.platform) {
32
+ case 'darwin':
33
+ console.log(utils_1.chalk.green('$ brew install mkcert'));
34
+ console.log(utils_1.chalk.gray('# If you use firefox, please install nss.'));
35
+ console.log(utils_1.chalk.green('$ brew install nss'));
36
+ console.log(utils_1.chalk.green('$ mkcert -install'));
37
+ break;
38
+ case 'win32':
39
+ console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#windows'));
40
+ break;
41
+ case 'linux':
42
+ console.log(utils_1.chalk.green('Checkout https://github.com/FiloSottile/mkcert#linux'));
43
+ break;
44
+ default:
45
+ break;
46
+ }
47
+ throw new Error(`[HTTPS] mkcert not found.`);
48
+ }
49
+ let { key, cert, hosts } = httpsConfig;
50
+ hosts = hosts || defaultHttpsHosts;
51
+ if (!key || !cert) {
52
+ key = (0, path_1.join)(__dirname, 'umi.key.pem');
53
+ cert = (0, path_1.join)(__dirname, 'umi.pem');
54
+ }
55
+ // Generate cert and key files if they are not exist.
56
+ if (!(0, fs_1.existsSync)(key) || !(0, fs_1.existsSync)(cert)) {
57
+ utils_1.logger.wait('[HTTPS] Generating cert and key files...');
58
+ yield utils_1.execa.execa('mkcert', [
59
+ '-cert-file',
60
+ cert,
61
+ '-key-file',
62
+ key,
63
+ ...hosts,
64
+ ]);
65
+ }
66
+ // Create server
67
+ return https_1.default.createServer({
68
+ key: (0, fs_1.readFileSync)(key, 'utf-8'),
69
+ cert: (0, fs_1.readFileSync)(cert, 'utf-8'),
70
+ }, app);
71
+ });
72
+ }
73
+ exports.createHttpsServer = createHttpsServer;
@@ -11,6 +11,7 @@ interface IOpts {
11
11
  beforeMiddlewares?: any[];
12
12
  afterMiddlewares?: any[];
13
13
  onDevCompileDone?: Function;
14
+ onProgress?: Function;
14
15
  }
15
- export declare function createServer(opts: IOpts): Promise<http.Server>;
16
+ export declare function createServer(opts: IOpts): Promise<import("https").Server | http.Server | null>;
16
17
  export {};
@@ -13,7 +13,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.createServer = void 0;
16
- const express_1 = __importDefault(require("@umijs/bundler-webpack/compiled/express"));
16
+ const express_1 = __importDefault(require("@umijs/bundler-utils/compiled/express"));
17
17
  const http_proxy_middleware_1 = require("@umijs/bundler-webpack/compiled/http-proxy-middleware");
18
18
  const webpack_1 = __importDefault(require("@umijs/bundler-webpack/compiled/webpack"));
19
19
  const utils_1 = require("@umijs/utils");
@@ -21,6 +21,7 @@ const fs_1 = require("fs");
21
21
  const http_1 = __importDefault(require("http"));
22
22
  const path_1 = require("path");
23
23
  const constants_1 = require("../constants");
24
+ const https_1 = require("./https");
24
25
  const ws_1 = require("./ws");
25
26
  function createServer(opts) {
26
27
  return __awaiter(this, void 0, void 0, function* () {
@@ -42,7 +43,7 @@ function createServer(opts) {
42
43
  // cros
43
44
  app.use((_req, res, next) => {
44
45
  res.header('Access-Control-Allow-Origin', '*');
45
- res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
46
+ res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
46
47
  res.header('Access-Control-Allow-Methods', 'GET, HEAD, PUT, POST, PATCH, DELETE, OPTIONS');
47
48
  next();
48
49
  });
@@ -55,17 +56,35 @@ function createServer(opts) {
55
56
  app.use((req, res, next) => {
56
57
  if (req.path === '/umi.js' && (0, fs_1.existsSync)((0, path_1.join)(opts.cwd, 'umi.js'))) {
57
58
  res.setHeader('Content-Type', 'application/javascript');
58
- res.send((0, fs_1.readFileSync)((0, path_1.join)(opts.cwd, 'umi.js'), 'utf-8'));
59
+ (0, fs_1.createReadStream)((0, path_1.join)(opts.cwd, 'umi.js')).on('error', next).pipe(res);
59
60
  }
60
61
  else {
61
62
  next();
62
63
  }
63
64
  });
64
65
  // webpack dev middleware
65
- const compiler = (0, webpack_1.default)(Array.isArray(webpackConfig) ? webpackConfig : [webpackConfig]);
66
+ const configs = Array.isArray(webpackConfig)
67
+ ? webpackConfig
68
+ : [webpackConfig];
69
+ const progresses = [];
70
+ if (opts.onProgress) {
71
+ configs.forEach((config) => {
72
+ const progress = {
73
+ percent: 0,
74
+ status: 'waiting',
75
+ };
76
+ progresses.push(progress);
77
+ config.plugins.push(new webpack_1.default.ProgressPlugin((percent, msg) => {
78
+ progress.percent = percent;
79
+ progress.status = msg;
80
+ opts.onProgress({ progresses });
81
+ }));
82
+ });
83
+ }
84
+ const compiler = (0, webpack_1.default)(configs);
66
85
  const webpackDevMiddleware = require('@umijs/bundler-webpack/compiled/webpack-dev-middleware');
67
86
  const compilerMiddleware = webpackDevMiddleware(compiler, {
68
- publicPath: '/',
87
+ publicPath: userConfig.publicPath || '/',
69
88
  writeToDisk: userConfig.writeToDisk,
70
89
  stats: 'none',
71
90
  // watchOptions: { ignored }
@@ -133,11 +152,24 @@ function createServer(opts) {
133
152
  // proxy
134
153
  if (proxy) {
135
154
  Object.keys(proxy).forEach((key) => {
136
- app.use(key, (0, http_proxy_middleware_1.createProxyMiddleware)(proxy[key]));
155
+ const proxyConfig = proxy[key];
156
+ const target = proxyConfig.target;
157
+ if (target) {
158
+ app.use(key, (0, http_proxy_middleware_1.createProxyMiddleware)(key, Object.assign(Object.assign({}, proxy[key]), {
159
+ // Add x-real-url in response header
160
+ onProxyRes(proxyRes, req) {
161
+ var _a;
162
+ proxyRes.headers['x-real-url'] =
163
+ ((_a = new URL(req.url || '', target)) === null || _a === void 0 ? void 0 : _a.href) || '';
164
+ } })));
165
+ }
137
166
  });
138
167
  }
139
168
  // after middlewares
140
- (opts.afterMiddlewares || []).forEach((m) => app.use(m));
169
+ (opts.afterMiddlewares || []).forEach((m) => {
170
+ // TODO: FIXME
171
+ app.use(m.toString().includes(`{ compiler }`) ? m({ compiler }) : m);
172
+ });
141
173
  // history fallback
142
174
  app.use(require('@umijs/bundler-webpack/compiled/connect-history-api-fallback')({
143
175
  index: '/',
@@ -152,24 +184,29 @@ function createServer(opts) {
152
184
  res.set('Content-Type', 'text/html');
153
185
  const htmlPath = (0, path_1.join)(opts.cwd, 'index.html');
154
186
  if ((0, fs_1.existsSync)(htmlPath)) {
155
- const html = (0, fs_1.readFileSync)(htmlPath, 'utf-8');
156
- res.send(html);
187
+ (0, fs_1.createReadStream)(htmlPath).on('error', next).pipe(res);
157
188
  }
158
189
  else {
159
190
  next();
160
191
  }
161
192
  });
162
- const server = http_1.default.createServer(app);
193
+ const server = userConfig.https
194
+ ? yield (0, https_1.createHttpsServer)(app, userConfig.https)
195
+ : http_1.default.createServer(app);
196
+ if (!server) {
197
+ return null;
198
+ }
163
199
  const ws = (0, ws_1.createWebSocketServer)(server);
164
200
  ws.wss.on('connection', (socket) => {
165
201
  if (stats) {
166
202
  sendStats(getStats(stats), false, socket);
167
203
  }
168
204
  });
205
+ const protocol = userConfig.https ? 'https:' : 'http:';
169
206
  const port = opts.port || 8000;
170
207
  server.listen(port, () => {
171
208
  const host = opts.host && opts.host !== '0.0.0.0' ? opts.host : '127.0.0.1';
172
- utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`http://${host}:${port}`)}`);
209
+ utils_1.logger.ready(`App listening at ${utils_1.chalk.green(`${protocol}//${host}:${port}`)}`);
173
210
  });
174
211
  return server;
175
212
  });
@@ -1,7 +1,8 @@
1
1
  /// <reference types="node" />
2
- import { Server } from 'http';
2
+ import { Server as HttpServer } from 'http';
3
+ import { Server as HttpsServer } from 'https';
3
4
  import WebSocket from '../../compiled/ws';
4
- export declare function createWebSocketServer(server: Server): {
5
+ export declare function createWebSocketServer(server: HttpServer | HttpsServer): {
5
6
  send(message: string): void;
6
7
  wss: WebSocket.Server;
7
8
  close(): void;
@@ -1,8 +1,13 @@
1
- import { ImportDeclaration, TsType, VariableDeclaration } from '@swc/core';
1
+ import type { ImportDeclaration, ModuleItem, TsType } from '@swc/core';
2
2
  import Visitor from '@swc/core/Visitor';
3
3
  declare class AutoCSSModule extends Visitor {
4
4
  visitTsType(expression: TsType): TsType;
5
+ /**
6
+ * call path:
7
+ * visitProgram -> visitModule -> visitModuleItems -> visitModuleItem -> visitImportDeclaration
8
+ * @see https://github.com/swc-project/swc/blob/main/node-swc/src/Visitor.ts#L189
9
+ */
10
+ visitModuleItem(n: ModuleItem): ImportDeclaration | import("@swc/core").ExportDeclaration | import("@swc/core").ExportNamedDeclaration | import("@swc/core").ExportDefaultDeclaration | import("@swc/core").ExportDefaultExpression | import("@swc/core").ExportAllDeclaration | import("@swc/core").TsImportEqualsDeclaration | import("@swc/core").TsExportAssignment | import("@swc/core").TsNamespaceExportDeclaration | import("@swc/core").ExpressionStatement | import("@swc/core").BlockStatement | import("@swc/core").EmptyStatement | import("@swc/core").DebuggerStatement | import("@swc/core").WithStatement | import("@swc/core").ReturnStatement | import("@swc/core").LabeledStatement | import("@swc/core").BreakStatement | import("@swc/core").ContinueStatement | import("@swc/core").IfStatement | import("@swc/core").SwitchStatement | import("@swc/core").ThrowStatement | import("@swc/core").TryStatement | import("@swc/core").WhileStatement | import("@swc/core").DoWhileStatement | import("@swc/core").ForStatement | import("@swc/core").ForInStatement | import("@swc/core").ForOfStatement | import("@swc/core").ClassDeclaration | import("@swc/core").FunctionDeclaration | import("@swc/core").VariableDeclaration | import("@swc/core").TsInterfaceDeclaration | import("@swc/core").TsTypeAliasDeclaration | import("@swc/core").TsEnumDeclaration | import("@swc/core").TsModuleDeclaration;
5
11
  visitImportDeclaration(expression: ImportDeclaration): ImportDeclaration;
6
- visitVariableDeclaration(expression: VariableDeclaration): VariableDeclaration;
7
12
  }
8
13
  export default AutoCSSModule;
@@ -5,31 +5,28 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const Visitor_1 = __importDefault(require("@swc/core/Visitor"));
7
7
  const utils_1 = require("@umijs/utils");
8
+ const changeImportFromString_1 = require("./changeImportFromString");
8
9
  class AutoCSSModule extends Visitor_1.default {
9
10
  visitTsType(expression) {
10
11
  return expression;
11
12
  }
13
+ /**
14
+ * call path:
15
+ * visitProgram -> visitModule -> visitModuleItems -> visitModuleItem -> visitImportDeclaration
16
+ * @see https://github.com/swc-project/swc/blob/main/node-swc/src/Visitor.ts#L189
17
+ */
18
+ visitModuleItem(n) {
19
+ if (n.type === 'ImportDeclaration') {
20
+ return this.visitImportDeclaration(n);
21
+ }
22
+ return n;
23
+ }
12
24
  visitImportDeclaration(expression) {
13
25
  const { specifiers, source } = expression;
14
26
  const { value } = source;
15
27
  if (specifiers.length && (0, utils_1.isStyleFile)({ filename: value })) {
16
- return Object.assign(Object.assign({}, expression), { source: Object.assign(Object.assign({}, source), { value: `${value}?modules` }) });
17
- }
18
- return expression;
19
- }
20
- visitVariableDeclaration(expression) {
21
- const { declarations } = expression;
22
- if (declarations.length &&
23
- declarations[0].init &&
24
- declarations[0].init.type === 'AwaitExpression' &&
25
- declarations[0].init.argument.type === 'CallExpression' &&
26
- declarations[0].init.argument.arguments.length &&
27
- declarations[0].init.argument.arguments[0].expression.type ===
28
- 'StringLiteral' &&
29
- (0, utils_1.isStyleFile)({
30
- filename: declarations[0].init.argument.arguments[0].expression.value,
31
- })) {
32
- declarations[0].init.argument.arguments[0].expression.value = `${declarations[0].init.argument.arguments[0].expression.value}?modules`;
28
+ const newImportFrom = `${value}?modules`;
29
+ (0, changeImportFromString_1.changeImportFromString)(expression, newImportFrom);
33
30
  }
34
31
  return expression;
35
32
  }
@@ -0,0 +1,2 @@
1
+ import type { ImportDeclaration } from '@swc/core';
2
+ export declare const changeImportFromString: (e: ImportDeclaration, v: string) => void;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.changeImportFromString = void 0;
4
+ const changeImportFromString = (e, v) => {
5
+ e.source.value = v;
6
+ // sync change to `raw`
7
+ // https://github.com/swc-project/swc/issues/4128
8
+ e.source.raw = `'${v}'`;
9
+ };
10
+ exports.changeImportFromString = changeImportFromString;
@@ -1,4 +1,4 @@
1
- import { ImportDeclaration } from '@swc/core';
1
+ import type { ImportDeclaration } from '@swc/core';
2
2
  import Visitor from '@swc/core/Visitor';
3
3
  declare class LockCoreJS extends Visitor {
4
4
  visitImportDeclaration(expression: ImportDeclaration): ImportDeclaration;
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const Visitor_1 = __importDefault(require("@swc/core/Visitor"));
7
7
  const utils_1 = require("@umijs/utils");
8
8
  const path_1 = require("path");
9
+ const changeImportFromString_1 = require("./changeImportFromString");
9
10
  function addLastSlash(path) {
10
11
  return path.endsWith('/') ? path : `${path}/`;
11
12
  }
@@ -14,8 +15,8 @@ class LockCoreJS extends Visitor_1.default {
14
15
  const { source } = expression;
15
16
  let { value, type } = source;
16
17
  if (type === 'StringLiteral' && value.startsWith('core-js/')) {
17
- value = value.replace(/^core-js\//, addLastSlash((0, utils_1.winPath)((0, path_1.dirname)(require.resolve('core-js/package.json')))));
18
- return Object.assign(Object.assign({}, expression), { source: Object.assign(Object.assign({}, source), { value }) });
18
+ const newValue = value.replace(/^core-js\//, addLastSlash((0, utils_1.winPath)((0, path_1.dirname)(require.resolve('core-js/package.json')))));
19
+ (0, changeImportFromString_1.changeImportFromString)(expression, newValue);
19
20
  }
20
21
  return expression;
21
22
  }
package/dist/types.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import type { Config as SwcConfig } from '@swc/core';
2
- import type { ImportSpecifier } from '@umijs/bundler-utils/compiled/es-module-lexer';
3
- import type { TransformOptions } from '@umijs/bundler-utils/compiled/esbuild';
4
2
  import type { Options as ProxyOptions } from '../compiled/http-proxy-middleware';
5
3
  import { Configuration } from '../compiled/webpack';
6
4
  import Config from '../compiled/webpack-5-chain';
@@ -24,6 +22,7 @@ export declare enum JSMinifier {
24
22
  export declare enum CSSMinifier {
25
23
  esbuild = "esbuild",
26
24
  cssnano = "cssnano",
25
+ parcelCSS = "parcelCSS",
27
26
  none = "none"
28
27
  }
29
28
  export interface ICopy {
@@ -34,6 +33,19 @@ declare type WebpackConfig = Required<Configuration>;
34
33
  declare type IBabelPlugin = Function | string | [string, {
35
34
  [key: string]: any;
36
35
  }];
36
+ export interface DeadCodeParams {
37
+ patterns?: string[];
38
+ exclude?: string[];
39
+ failOnHint?: boolean;
40
+ detectUnusedFiles?: boolean;
41
+ detectUnusedExport?: boolean;
42
+ context?: string;
43
+ }
44
+ export interface HttpsParams {
45
+ key?: string;
46
+ cert?: string;
47
+ hosts?: string[];
48
+ }
37
49
  export interface IConfig {
38
50
  alias?: Record<string, string>;
39
51
  autoCSSModules?: boolean;
@@ -55,6 +67,8 @@ export interface IConfig {
55
67
  };
56
68
  depTranspiler?: Transpiler;
57
69
  devtool?: Config.DevTool;
70
+ deadCode?: DeadCodeParams;
71
+ https?: HttpsParams;
58
72
  externals?: WebpackConfig['externals'];
59
73
  esm?: {
60
74
  [key: string]: any;
@@ -104,15 +118,5 @@ export interface IConfig {
104
118
  export interface SwcOptions extends SwcConfig {
105
119
  sync?: boolean;
106
120
  parseMap?: boolean;
107
- targets?: Record<string, any>;
108
- }
109
- export interface IEsbuildLoaderHandlerParams {
110
- code: string;
111
- filePath: string;
112
- imports: readonly ImportSpecifier[];
113
- exports: readonly string[];
114
- }
115
- export interface IEsbuildLoaderOpts extends Partial<TransformOptions> {
116
- handler?: Array<(opts: IEsbuildLoaderHandlerParams) => string>;
117
121
  }
118
122
  export {};
package/dist/types.js CHANGED
@@ -25,5 +25,6 @@ var CSSMinifier;
25
25
  (function (CSSMinifier) {
26
26
  CSSMinifier["esbuild"] = "esbuild";
27
27
  CSSMinifier["cssnano"] = "cssnano";
28
+ CSSMinifier["parcelCSS"] = "parcelCSS";
28
29
  CSSMinifier["none"] = "none";
29
30
  })(CSSMinifier = exports.CSSMinifier || (exports.CSSMinifier = {}));
@@ -15,7 +15,7 @@ function isMatch(opts) {
15
15
  return !!cache.get(dir);
16
16
  }
17
17
  else {
18
- const pkgPath = utils_1.pkgUp.sync({ cwd: opts.path });
18
+ const pkgPath = utils_1.pkgUp.pkgUpSync({ cwd: opts.path });
19
19
  let ret;
20
20
  if (!pkgPath) {
21
21
  ret = false;
@@ -0,0 +1,5 @@
1
+ interface IOpts {
2
+ targets: Record<string, any>;
3
+ }
4
+ export declare function getEsBuildTarget({ targets }: IOpts): string[];
5
+ export {};
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getEsBuildTarget = void 0;
4
+ const constants_1 = require("../constants");
5
+ function getEsBuildTarget({ targets }) {
6
+ return Object.keys(targets)
7
+ .filter((key) => constants_1.DEFAULT_ESBUILD_TARGET_KEYS.includes(key))
8
+ .map((key) => {
9
+ return `${key}${targets[key] === true ? '0' : targets[key]}`;
10
+ });
11
+ }
12
+ exports.getEsBuildTarget = getEsBuildTarget;