@shuvi/toolpack 1.0.0-rc.0 → 1.0.0-rc.11

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 (90) hide show
  1. package/lib/babel/plugins/{loadable-plugin.d.ts → dynamic-plugin.d.ts} +1 -1
  2. package/lib/babel/plugins/{loadable-plugin.js → dynamic-plugin.js} +8 -8
  3. package/lib/babel/preset.js +1 -1
  4. package/lib/constants.d.ts +1 -0
  5. package/lib/constants.js +2 -1
  6. package/lib/utils/formatWebpackMessages.d.ts +18 -4
  7. package/lib/utils/formatWebpackMessages.js +15 -13
  8. package/lib/webpack/config/base.d.ts +3 -1
  9. package/lib/webpack/config/base.js +43 -22
  10. package/lib/webpack/config/browser.js +47 -31
  11. package/lib/webpack/config/node.js +3 -3
  12. package/lib/webpack/config/parts/helpers.d.ts +1 -0
  13. package/lib/webpack/config/parts/helpers.js +8 -1
  14. package/lib/webpack/dynamic-dll/bundler/webpack-config.js +1 -1
  15. package/lib/webpack/dynamic-dll/index.d.ts +2 -2
  16. package/lib/webpack/dynamic-dll/index.js +26 -26
  17. package/lib/webpack/dynamic-dll/plugin/dynamic-dll-plugin.js +0 -1
  18. package/lib/webpack/index.d.ts +3 -5
  19. package/lib/webpack/index.js +4 -6
  20. package/lib/webpack/loaders/parcel-css-loader/CssSyntaxError.d.ts +9 -2
  21. package/lib/webpack/loaders/parcel-css-loader/CssSyntaxError.js +2 -1
  22. package/lib/webpack/loaders/shuvi-swc-loader/getLoaderSWCOptions.d.ts +94 -0
  23. package/lib/webpack/loaders/shuvi-swc-loader/getLoaderSWCOptions.js +162 -0
  24. package/lib/webpack/loaders/{shuvi-swc-loader.d.ts → shuvi-swc-loader/index.d.ts} +0 -0
  25. package/lib/webpack/loaders/{shuvi-swc-loader.js → shuvi-swc-loader/index.js} +50 -86
  26. package/lib/webpack/plugins/dynamic-public-path-plugin.js +3 -2
  27. package/lib/webpack/plugins/module-replace-plugin/plugin.d.ts +1 -0
  28. package/lib/webpack/plugins/module-replace-plugin/plugin.js +9 -1
  29. package/package.json +16 -50
  30. package/lib/swc/tests/fixture/auto-css-module/no-flag/input.d.ts +0 -1
  31. package/lib/swc/tests/fixture/auto-css-module/no-flag/input.js +0 -4
  32. package/lib/swc/tests/fixture/auto-css-module/no-flag/output.d.ts +0 -1
  33. package/lib/swc/tests/fixture/auto-css-module/no-flag/output.js +0 -4
  34. package/lib/swc/tests/fixture/auto-css-module/with-flag/input.d.ts +0 -1
  35. package/lib/swc/tests/fixture/auto-css-module/with-flag/input.js +0 -2
  36. package/lib/swc/tests/fixture/auto-css-module/with-flag/output.d.ts +0 -1
  37. package/lib/swc/tests/fixture/auto-css-module/with-flag/output.js +0 -2
  38. package/lib/swc/tests/fixture/shuvi-dynamic/duplicated-imports/input.d.ts +0 -1
  39. package/lib/swc/tests/fixture/shuvi-dynamic/duplicated-imports/input.js +0 -5
  40. package/lib/swc/tests/fixture/shuvi-dynamic/duplicated-imports/output.d.ts +0 -1
  41. package/lib/swc/tests/fixture/shuvi-dynamic/duplicated-imports/output.js +0 -11
  42. package/lib/swc/tests/fixture/shuvi-dynamic/member-with-same-name/input.d.ts +0 -1
  43. package/lib/swc/tests/fixture/shuvi-dynamic/member-with-same-name/input.js +0 -9
  44. package/lib/swc/tests/fixture/shuvi-dynamic/member-with-same-name/output.d.ts +0 -1
  45. package/lib/swc/tests/fixture/shuvi-dynamic/member-with-same-name/output.js +0 -12
  46. package/lib/swc/tests/fixture/shuvi-dynamic/no-options/input.d.ts +0 -1
  47. package/lib/swc/tests/fixture/shuvi-dynamic/no-options/input.js +0 -4
  48. package/lib/swc/tests/fixture/shuvi-dynamic/no-options/output.d.ts +0 -1
  49. package/lib/swc/tests/fixture/shuvi-dynamic/no-options/output.js +0 -7
  50. package/lib/swc/tests/fixture/shuvi-dynamic/with-options/input.d.ts +0 -1
  51. package/lib/swc/tests/fixture/shuvi-dynamic/with-options/input.js +0 -4
  52. package/lib/swc/tests/fixture/shuvi-dynamic/with-options/output.d.ts +0 -1
  53. package/lib/swc/tests/fixture/shuvi-dynamic/with-options/output.js +0 -8
  54. package/lib/swc/tests/fixture/shuvi-dynamic/wrapped-import/input.d.ts +0 -1
  55. package/lib/swc/tests/fixture/shuvi-dynamic/wrapped-import/input.js +0 -7
  56. package/lib/swc/tests/fixture/shuvi-dynamic/wrapped-import/output.d.ts +0 -1
  57. package/lib/swc/tests/fixture/shuvi-dynamic/wrapped-import/output.js +0 -9
  58. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/duplicated-imports/input.d.ts +0 -1
  59. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/duplicated-imports/input.js +0 -5
  60. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/duplicated-imports/output.d.ts +0 -1
  61. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/duplicated-imports/output.js +0 -11
  62. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/member-with-same-name/input.d.ts +0 -1
  63. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/member-with-same-name/input.js +0 -9
  64. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/member-with-same-name/output.d.ts +0 -1
  65. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/member-with-same-name/output.js +0 -12
  66. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/no-options/input.d.ts +0 -1
  67. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/no-options/input.js +0 -4
  68. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/no-options/output.d.ts +0 -1
  69. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/no-options/output.js +0 -7
  70. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/with-options/input.d.ts +0 -1
  71. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/with-options/input.js +0 -4
  72. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/with-options/output.d.ts +0 -1
  73. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/with-options/output.js +0 -8
  74. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/wrapped-import/input.d.ts +0 -1
  75. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/wrapped-import/input.js +0 -7
  76. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/wrapped-import/output.d.ts +0 -1
  77. package/lib/swc/tests/fixture/shuvi-dynamic-disabled/wrapped-import/output.js +0 -9
  78. package/lib/swc/tests/full/auto-cjs/1/input.d.ts +0 -1
  79. package/lib/swc/tests/full/auto-cjs/1/input.js +0 -8
  80. package/lib/swc/tests/full/auto-cjs/1/output.d.ts +0 -1
  81. package/lib/swc/tests/full/auto-cjs/1/output.js +0 -8
  82. package/lib/utils/build-loaders.d.ts +0 -2
  83. package/lib/utils/build-loaders.js +0 -131
  84. package/lib/utils/hotDevClient/eventsource.d.ts +0 -1
  85. package/lib/utils/hotDevClient/eventsource.js +0 -64
  86. package/lib/utils/hotDevClient/index.d.ts +0 -4
  87. package/lib/utils/hotDevClient/index.js +0 -362
  88. package/lib/utils/load-sources.d.ts +0 -3
  89. package/lib/utils/load-sources.js +0 -94
  90. package/swc-source/native/shuvi-swc.darwin-arm64.node +0 -0
@@ -19,6 +19,6 @@ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
19
19
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
20
20
  */
21
21
  import { PluginObj, types as BabelTypes } from '@babel/core';
22
- export default function ({ types: t, }: {
22
+ export default function ({ types: t }: {
23
23
  types: typeof BabelTypes;
24
24
  }): PluginObj;
@@ -23,14 +23,14 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWAR
23
23
  // This file is https://github.com/jamiebuilds/react-loadable/blob/master/src/babel.js
24
24
  // Modified to also look for `shuvi/dynamic`
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- function default_1({ types: t, }) {
26
+ function default_1({ types: t }) {
27
27
  return {
28
28
  visitor: {
29
29
  ImportDeclaration(path) {
30
30
  let source = path.node.source.value;
31
31
  if (source !== '@shuvi/runtime')
32
32
  return;
33
- let dynamicSpecifier = path.get('specifiers').find((specifier) => {
33
+ let dynamicSpecifier = path.get('specifiers').find(specifier => {
34
34
  return specifier.node.imported.name === 'dynamic';
35
35
  });
36
36
  if (!dynamicSpecifier)
@@ -40,7 +40,7 @@ function default_1({ types: t, }) {
40
40
  if (!binding) {
41
41
  return;
42
42
  }
43
- binding.referencePaths.forEach((refPath) => {
43
+ binding.referencePaths.forEach(refPath => {
44
44
  const callExpression = refPath.parentPath;
45
45
  if (!callExpression.isCallExpression())
46
46
  return;
@@ -68,7 +68,7 @@ function default_1({ types: t, }) {
68
68
  return;
69
69
  let properties = options.get('properties');
70
70
  let propertiesMap = {};
71
- properties.forEach((property) => {
71
+ properties.forEach(property => {
72
72
  const key = property.get('key');
73
73
  propertiesMap[key.node.name] = property;
74
74
  });
@@ -89,17 +89,17 @@ function default_1({ types: t, }) {
89
89
  return;
90
90
  const node = args[0].node;
91
91
  dynamicImports.push(node);
92
- },
92
+ }
93
93
  });
94
94
  if (!dynamicImports.length)
95
95
  return;
96
- options.node.properties.push(t.objectProperty(t.identifier('webpack'), t.arrowFunctionExpression([], t.arrayExpression(dynamicImports.map((dynamicImport) => {
96
+ options.node.properties.push(t.objectProperty(t.identifier('webpack'), t.arrowFunctionExpression([], t.arrayExpression(dynamicImports.map(dynamicImport => {
97
97
  return t.callExpression(t.memberExpression(t.identifier('require'), t.identifier('resolveWeak')), [dynamicImport]);
98
98
  })))));
99
99
  options.node.properties.push(t.objectProperty(t.identifier('modules'), t.arrayExpression(dynamicImports)));
100
100
  });
101
- },
102
- },
101
+ }
102
+ }
103
103
  };
104
104
  }
105
105
  exports.default = default_1;
@@ -89,7 +89,7 @@ exports.default = (api, options = {}) => {
89
89
  }
90
90
  ],
91
91
  require('@babel/plugin-syntax-dynamic-import'),
92
- require('./plugins/loadable-plugin'),
92
+ require('./plugins/dynamic-plugin'),
93
93
  require('@babel/plugin-proposal-class-properties'),
94
94
  [
95
95
  require('@babel/plugin-proposal-object-rest-spread'),
@@ -1 +1,2 @@
1
1
  export declare const AppSourceRegexs: RegExp[];
2
+ export declare const CommonChunkFilename = "static/common/[name].js";
package/lib/constants.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AppSourceRegexs = void 0;
3
+ exports.CommonChunkFilename = exports.AppSourceRegexs = void 0;
4
4
  exports.AppSourceRegexs = [
5
5
  /([/\\]shuvi-app[/\\])|([/\\]\.shuvi[/\\])/
6
6
  ];
7
+ exports.CommonChunkFilename = 'static/common/[name].js';
@@ -1,5 +1,19 @@
1
- export default formatWebpackMessages;
2
- declare function formatWebpackMessages(json: any): {
3
- errors: any;
4
- warnings: any;
1
+ /**
2
+ * Copyright (c) 2015-present, Facebook, Inc.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ */
7
+ interface StatsError {
8
+ moduleName?: string;
9
+ file?: string;
10
+ message?: string;
11
+ }
12
+ declare function formatWebpackMessages(json: {
13
+ warnings?: StatsError[];
14
+ errors?: StatsError[];
15
+ }): {
16
+ errors: string[];
17
+ warnings: string[];
5
18
  };
19
+ export default formatWebpackMessages;
@@ -1,22 +1,24 @@
1
+ "use strict";
1
2
  /**
2
3
  * Copyright (c) 2015-present, Facebook, Inc.
3
4
  *
4
5
  * This source code is licensed under the MIT license found in the
5
6
  * LICENSE file in the root directory of this source tree.
6
7
  */
7
- 'use strict';
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
9
- const chalk = require('@shuvi/utils/lib/chalk').default;
12
+ const chalk_1 = __importDefault(require("@shuvi/utils/lib/chalk"));
10
13
  const friendlySyntaxErrorLabel = 'Syntax error:';
11
14
  function isLikelyASyntaxError(message) {
12
15
  return message.indexOf(friendlySyntaxErrorLabel) !== -1;
13
16
  }
14
17
  // Cleans up webpack error messages.
15
- function formatMessage(message, isError) {
16
- message =
17
- (message.moduleName ? message.moduleName + '\n' : '') +
18
- (message.file ? message.file + '\n' : '') +
19
- message.message;
18
+ function formatMessage(stats, isError) {
19
+ let message = (stats.moduleName ? stats.moduleName + '\n' : '') +
20
+ (stats.file ? stats.file + '\n' : '') +
21
+ stats.message;
20
22
  let lines = message.split('\n');
21
23
  // Strip Webpack-added headers off errors/warnings
22
24
  // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
@@ -55,12 +57,12 @@ function formatMessage(message, isError) {
55
57
  ];
56
58
  }
57
59
  // Add helpful message for users trying to use Sass for the first time
58
- if (lines[1] && lines[1].match(/Cannot find module.+node-sass/)) {
59
- lines[1] = 'To import Sass files, you first need to install node-sass.\n';
60
+ if (lines[1] && lines[1].match(/Cannot find module.+sass/)) {
61
+ lines[1] = 'To import Sass files, you first need to install sass.\n';
60
62
  lines[1] +=
61
- 'Run `npm install node-sass` or `yarn add node-sass` inside your workspace.';
63
+ 'Run `npm install sass` or `yarn add sass` inside your workspace.';
62
64
  }
63
- lines[0] = chalk.inverse(lines[0]);
65
+ lines[0] = chalk_1.default.inverse(lines[0]);
64
66
  message = lines.join('\n');
65
67
  // Internal stacks are generally useless so we strip them... with the
66
68
  // exception of stacks containing `webpack:` because they're normally
@@ -76,10 +78,10 @@ function formatMessage(message, isError) {
76
78
  return message.trim();
77
79
  }
78
80
  function formatWebpackMessages(json) {
79
- const formattedErrors = json.errors.map(function (message) {
81
+ const formattedErrors = (json.errors || []).map(function (message) {
80
82
  return formatMessage(message, true);
81
83
  });
82
- const formattedWarnings = json.warnings.map(function (message) {
84
+ const formattedWarnings = (json.warnings || []).map(function (message) {
83
85
  return formatMessage(message, false);
84
86
  });
85
87
  const result = { errors: formattedErrors, warnings: formattedWarnings };
@@ -21,6 +21,8 @@ export interface BaseOptions {
21
21
  env?: {
22
22
  [x: string]: string | undefined;
23
23
  };
24
+ experimental?: Record<string, any>;
25
+ compiler?: Record<string, any>;
24
26
  }
25
27
  export { WebpackChain };
26
- export declare function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typescript, name, buildManifestFilename, publicPath, env, cacheDir }: BaseOptions): WebpackChain;
28
+ export declare function baseWebpackChain({ dev, outputDir, parcelCss, experimental, compiler, projectRoot, include, typescript, name, buildManifestFilename, publicPath, env, cacheDir }: BaseOptions): WebpackChain;
@@ -35,12 +35,12 @@ const webpack_1 = __importDefault(require("webpack"));
35
35
  const path = __importStar(require("path"));
36
36
  const constants_1 = require("@shuvi/shared/lib/constants");
37
37
  const build_manifest_plugin_1 = __importDefault(require("../plugins/build-manifest-plugin"));
38
- const chunk_names_plugin_1 = __importDefault(require("../plugins/chunk-names-plugin"));
39
38
  const fix_watching_plugin_1 = __importDefault(require("../plugins/fix-watching-plugin"));
40
39
  const constants_2 = require("../../constants");
41
40
  const crypto = __importStar(require("crypto"));
42
41
  const jsconfig_paths_plugin_1 = __importDefault(require("../plugins/jsconfig-paths-plugin"));
43
42
  const support_ts_extension_resolver_plugin_1 = __importDefault(require("../plugins/support-ts-extension-resolver-plugin"));
43
+ const helpers_1 = require("./parts/helpers");
44
44
  const resolveLocalLoader = (name) => path.join(__dirname, `../loaders/${name}`);
45
45
  const terserOptions = {
46
46
  parse: {
@@ -61,23 +61,54 @@ const terserOptions = {
61
61
  ascii_only: true
62
62
  }
63
63
  };
64
- function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typescript, name, buildManifestFilename, publicPath = '/', env = {}, cacheDir }) {
64
+ function baseWebpackChain({ dev, outputDir, parcelCss, experimental, compiler, projectRoot, include, typescript, name, buildManifestFilename, publicPath = '/', env = {}, cacheDir }) {
65
65
  var _a;
66
66
  const config = new webpack_chain_1.default();
67
67
  config.mode(dev ? 'development' : 'production');
68
68
  config.bail(!dev);
69
69
  config.performance.hints(false);
70
70
  config.context(projectRoot);
71
+ config.output.path(outputDir);
72
+ config.output.merge({
73
+ publicPath,
74
+ filename: `${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
75
+ // This saves chunks with the name given via `import()`
76
+ chunkFilename: `static/chunks/${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
77
+ hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
78
+ hotUpdateMainFilename: 'static/webpack/[fullhash].hot-update.json',
79
+ strictModuleExceptionHandling: true,
80
+ // crossOriginLoading: crossOrigin,
81
+ webassemblyModuleFilename: 'static/wasm/[modulehash:8].wasm',
82
+ hashFunction: 'xxhash64',
83
+ hashDigestLength: 16
84
+ });
71
85
  config.optimization.merge({
72
86
  emitOnErrors: !dev,
73
87
  checkWasmTypes: false,
74
88
  nodeEnv: false,
75
- splitChunks: false,
76
89
  runtimeChunk: undefined,
77
90
  minimize: !dev,
78
91
  realContentHash: false
79
92
  });
80
- if (!dev) {
93
+ if (dev) {
94
+ config.optimization.usedExports(false);
95
+ config.optimization.splitChunks({
96
+ chunks: helpers_1.splitChunksFilter,
97
+ cacheGroups: {
98
+ defaultVendors: false,
99
+ default: false,
100
+ vendors: {
101
+ name: 'vendors',
102
+ filename: constants_2.CommonChunkFilename,
103
+ test: /[\\/]node_modules[\\/]/,
104
+ // Don't let webpack eliminate this chunk (prevents this chunk from
105
+ // becoming a part of the commons chunk)
106
+ enforce: true
107
+ }
108
+ }
109
+ });
110
+ }
111
+ else {
81
112
  // @ts-ignore
82
113
  config.optimization.minimizer('terser').use(terser_webpack_plugin_1.default, [
83
114
  {
@@ -95,18 +126,6 @@ function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typ
95
126
  }
96
127
  ]);
97
128
  }
98
- config.output.path(outputDir);
99
- config.output.merge({
100
- publicPath,
101
- filename: `${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
102
- // This saves chunks with the name given via `import()`
103
- chunkFilename: `static/chunks/${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
104
- hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
105
- hotUpdateMainFilename: 'static/webpack/[fullhash].hot-update.json',
106
- strictModuleExceptionHandling: true,
107
- // crossOriginLoading: crossOrigin,
108
- webassemblyModuleFilename: 'static/wasm/[modulehash:8].wasm'
109
- });
110
129
  // Support for NODE_PATH
111
130
  const nodePathList = (process.env.NODE_PATH || '')
112
131
  .split(process.platform === 'win32' ? ';' : ':')
@@ -144,8 +163,13 @@ function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typ
144
163
  .use('shuvi-swc-loader')
145
164
  .loader('@shuvi/shuvi-swc-loader')
146
165
  .options({
147
- isNode: false
166
+ isServer: false,
167
+ experimental,
168
+ compiler,
169
+ supportedBrowsers: false,
170
+ swcCacheDir: path.join(cacheDir, 'swc')
148
171
  });
172
+ config.resolve.alias.set('@swc/helpers', path.dirname(require.resolve(`@swc/helpers/package.json`)));
149
173
  mainRule
150
174
  .oneOf('media')
151
175
  .exclude.merge([/\.(tsx|ts|js|cjs|mjs|jsx)$/, /\.html$/, /\.json$/])
@@ -155,7 +179,6 @@ function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typ
155
179
  .options({
156
180
  name: 'static/media/[name].[hash:8].[ext]'
157
181
  });
158
- config.plugin('chunk-names').use(chunk_names_plugin_1.default);
159
182
  config.plugin('private/ignore-plugin').use(webpack_1.default.IgnorePlugin, [
160
183
  {
161
184
  resourceRegExp: /^\.\/locale$/,
@@ -218,15 +241,13 @@ function baseWebpackChain({ dev, outputDir, parcelCss, projectRoot, include, typ
218
241
  if (dev) {
219
242
  // For webpack-dev-middleware usage
220
243
  config.watchOptions({
221
- // timeout 300 will make hmr.test to failed, set to 350
222
- aggregateTimeout: 350,
223
- ignored: ['**/.git/**', '**/node_modules/**']
244
+ aggregateTimeout: 5,
245
+ ignored: ['**/.git/**']
224
246
  });
225
247
  config.set('infrastructureLogging', {
226
248
  level: 'none'
227
249
  });
228
250
  config.plugin('private/fix-watching-plugin').use(fix_watching_plugin_1.default);
229
- config.optimization.usedExports(false);
230
251
  }
231
252
  else {
232
253
  config
@@ -32,10 +32,24 @@ const webpack_1 = __importDefault(require("webpack"));
32
32
  const path = __importStar(require("path"));
33
33
  const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
34
34
  const resolve_1 = require("@shuvi/utils/lib/resolve");
35
- const dynamic_public_path_plugin_1 = __importDefault(require("../plugins/dynamic-public-path-plugin"));
35
+ const constants_1 = require("../../constants");
36
36
  const base_1 = require("./base");
37
37
  const style_1 = require("./parts/style");
38
+ const helpers_1 = require("./parts/helpers");
38
39
  const BIG_LIBRARY_THRESHOLD = 160000; // byte
40
+ const SHUVI_PKGS_REGEX = /[\\/]node_modules[\\/]@shuvi[\\/]/;
41
+ const FRAMEWORK_REACT_MODULES = [
42
+ {
43
+ test: /[/\\]node_modules[/\\]react[/\\]/
44
+ },
45
+ {
46
+ test: /[/\\]node_modules[/\\]react-dom[/\\]/
47
+ },
48
+ {
49
+ test: /[/\\]node_modules[/\\]scheduler[/\\]/,
50
+ issuers: [/[/\\]node_modules[/\\]react-dom[/\\]/]
51
+ }
52
+ ];
39
53
  function createBrowserWebpackChain(options) {
40
54
  const { cacheDir, typescript, dev, publicPath, analyze } = options;
41
55
  const chain = (0, base_1.baseWebpackChain)(options);
@@ -79,27 +93,46 @@ function createBrowserWebpackChain(options) {
79
93
  }
80
94
  ]);
81
95
  }
82
- // if (options.target) {
83
- // chain.resolve
84
- // .plugin('private/prefer-resolver-plugin')
85
- // .use(PreferResolverPlugin, [{ suffix: options.target }]);
86
- // }
87
96
  if (dev) {
88
97
  chain.plugin('private/hmr-plugin').use(webpack_1.default.HotModuleReplacementPlugin);
89
98
  }
90
99
  else {
91
100
  chain.optimization.splitChunks({
92
- chunks: 'all',
101
+ chunks: helpers_1.splitChunksFilter,
93
102
  cacheGroups: {
94
103
  default: false,
95
104
  defaultVendors: false,
96
105
  framework: {
97
106
  chunks: 'all',
98
107
  name: 'framework',
99
- // This regex ignores nested copies of framework libraries so they're
100
- // bundled with their issuer.
101
- // https://github.com/zeit/next.js/pull/9012
102
- test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|@shuvi\/router|@shuvi\/router-react|scheduler|prop-types|use-sync-external-store|history)[\\/]/,
108
+ filename: constants_1.CommonChunkFilename,
109
+ test(module) {
110
+ const resource = module.nameForCondition();
111
+ if (!resource) {
112
+ return false;
113
+ }
114
+ if (SHUVI_PKGS_REGEX.test(resource)) {
115
+ return true;
116
+ }
117
+ return FRAMEWORK_REACT_MODULES.some(frameworkModule => {
118
+ if (!frameworkModule.test.test(resource)) {
119
+ return false;
120
+ }
121
+ // Check issuer to ignore nested copies of framework libraries so they're
122
+ // bundled with their issuer.
123
+ // https://github.com/zeit/next.js/pull/9012
124
+ if (frameworkModule.issuers) {
125
+ for (const issuer of frameworkModule.issuers) {
126
+ const issuerResource = module.issuer.nameForCondition();
127
+ if (!issuer.test(issuerResource)) {
128
+ return false;
129
+ }
130
+ }
131
+ }
132
+ return true;
133
+ });
134
+ },
135
+ // test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|@shuvi[\\/]router|@shuvi[\\/]router-react|scheduler|prop-types|use-sync-external-store|history)[\\/]/,
103
136
  priority: 40,
104
137
  // Don't let webpack eliminate this chunk (prevents this chunk from
105
138
  // becoming a part of the commons chunk)
@@ -108,7 +141,7 @@ function createBrowserWebpackChain(options) {
108
141
  lib: {
109
142
  test(module) {
110
143
  return (module.size() > BIG_LIBRARY_THRESHOLD &&
111
- /node_modules[/\\]/.test(module.identifier()));
144
+ /[/\\]node_modules[/\\]/.test(module.nameForCondition() || ''));
112
145
  },
113
146
  name(module) {
114
147
  const hash = crypto.createHash('sha1');
@@ -123,27 +156,10 @@ function createBrowserWebpackChain(options) {
123
156
  }
124
157
  return hash.digest('hex').substring(0, 8);
125
158
  },
159
+ filename: constants_1.CommonChunkFilename,
126
160
  priority: 30,
127
161
  minChunks: 1,
128
162
  reuseExistingChunk: true
129
- },
130
- commons: {
131
- name: 'commons',
132
- minChunks: 2,
133
- priority: 20
134
- },
135
- shared: {
136
- name(module, chunks) {
137
- return crypto
138
- .createHash('sha1')
139
- .update(chunks.reduce((acc, chunk) => {
140
- return acc + chunk.name;
141
- }, ''))
142
- .digest('hex');
143
- },
144
- priority: 10,
145
- minChunks: 2,
146
- reuseExistingChunk: true
147
163
  }
148
164
  },
149
165
  maxInitialRequests: 25,
@@ -185,7 +201,7 @@ function createBrowserWebpackChain(options) {
185
201
  // prevent errof of destructing process.env
186
202
  'process.env': JSON.stringify('{}') })
187
203
  ]);
188
- chain.plugin('dynamic-public-path-plugin').use(dynamic_public_path_plugin_1.default);
204
+ // chain.plugin('dynamic-public-path-plugin').use(DynamicPublicPathPlugin);
189
205
  chain.plugin('private/build-manifest').tap(([options]) => [
190
206
  Object.assign(Object.assign({}, options), { modules: true })
191
207
  ]);
@@ -5,11 +5,11 @@ const base_1 = require("./base");
5
5
  const external_1 = require("./parts/external");
6
6
  const style_1 = require("./parts/style");
7
7
  function createNodeWebpackChain(options) {
8
- const { webpackHelpers, typescript } = options;
8
+ const { webpackHelpers, typescript, dev } = options;
9
9
  const chain = (0, base_1.baseWebpackChain)(options);
10
10
  const useTypeScript = !!(typescript === null || typescript === void 0 ? void 0 : typescript.useTypeScript);
11
11
  chain.target('node');
12
- chain.devtool(false);
12
+ chain.devtool(dev ? 'cheap-module-source-map' : false);
13
13
  chain.resolve.extensions.merge([
14
14
  ...(useTypeScript ? ['.ts', '.tsx'] : []),
15
15
  '.js',
@@ -31,7 +31,7 @@ function createNodeWebpackChain(options) {
31
31
  .rule('main')
32
32
  .oneOf('js')
33
33
  .use('shuvi-swc-loader')
34
- .tap(options => (Object.assign(Object.assign({}, options), { isNode: true })));
34
+ .tap(options => (Object.assign(Object.assign({}, options), { isServer: true })));
35
35
  chain.plugin('private/build-manifest').tap(([options]) => [
36
36
  Object.assign(Object.assign({}, options), { modules: false })
37
37
  ]);
@@ -1,3 +1,4 @@
1
1
  import { IWebpackHelpers } from '../../types';
2
2
  export declare const webpackHelpers: () => IWebpackHelpers;
3
3
  export declare function shouldUseRelativeAssetPaths(publicPath: string): boolean;
4
+ export declare function splitChunksFilter(chunk: any): boolean;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.shouldUseRelativeAssetPaths = exports.webpackHelpers = void 0;
3
+ exports.splitChunksFilter = exports.shouldUseRelativeAssetPaths = exports.webpackHelpers = void 0;
4
4
  const webpackHelpers = () => {
5
5
  const externalFns = [];
6
6
  const defaultExternalsFn = ({ context, request }, callback) => {
@@ -48,3 +48,10 @@ function shouldUseRelativeAssetPaths(publicPath) {
48
48
  return publicPath === './';
49
49
  }
50
50
  exports.shouldUseRelativeAssetPaths = shouldUseRelativeAssetPaths;
51
+ function splitChunksFilter(chunk) {
52
+ const excludes = {
53
+ 'static/polyfill': true
54
+ };
55
+ return excludes[chunk.name] !== true;
56
+ }
57
+ exports.splitChunksFilter = splitChunksFilter;
@@ -37,7 +37,7 @@ function getConfig({ name, entry, filename, outputDir, publicPath, shared, exter
37
37
  config.optimization.merge({
38
38
  emitOnErrors: true,
39
39
  checkWasmTypes: false,
40
- // TODO: need to use DefinePlugin to set process.env.NODE_ENV
40
+ // need to use DefinePlugin to set process.env.NODE_ENV
41
41
  nodeEnv: false,
42
42
  runtimeChunk: false,
43
43
  minimize: false,
@@ -1,8 +1,9 @@
1
1
  import { IncomingMessage, ServerResponse } from 'http';
2
+ import type * as webpackType from 'webpack';
2
3
  import type { Configuration } from 'webpack';
3
4
  import type WebpackChain from 'webpack-chain';
4
5
  import { ShareConfig } from './bundler';
5
- declare type IResolveWebpackModule = <T extends string>(path: T) => T extends `webpack/${infer R}` ? any : never;
6
+ declare type IResolveWebpackModule = <T extends string>(path: T) => T extends `webpack` ? typeof webpackType : T extends `webpack/${infer R}` ? any : never;
6
7
  interface IOpts {
7
8
  cwd?: string;
8
9
  rootDir: string;
@@ -29,7 +30,6 @@ export declare class DynamicDll {
29
30
  modifyWebpackChain: (chain: WebpackChain) => WebpackChain;
30
31
  modifyWebpack: (config: Configuration) => Configuration;
31
32
  private _buildDLL;
32
- private _makeAsyncEntry;
33
33
  private _getMFconfig;
34
34
  }
35
35
  export {};
@@ -24,6 +24,30 @@ const dynamic_dll_plugin_1 = require("./plugin/dynamic-dll-plugin");
24
24
  const metadata_1 = require("./metadata");
25
25
  const utils_1 = require("./utils");
26
26
  const check_not_in_node_modules_1 = require("./helper/check-not-in-node-modules");
27
+ function makeAsyncEntry(entry) {
28
+ const asyncEntry = {};
29
+ const virtualModules = {};
30
+ const entryObject = ((0, utils_1.isString)(entry) || (0, utils_1.isArray)(entry)
31
+ ? { main: [].concat(entry) }
32
+ : entry);
33
+ for (const key of Object.keys(entryObject)) {
34
+ const virtualPath = `./dynamic-dll-virtual-entry/${key}.js`;
35
+ const virtualContent = [];
36
+ const entryFiles = (0, utils_1.isArray)(entryObject[key])
37
+ ? entryObject[key]
38
+ : [entryObject[key]];
39
+ for (let entry of entryFiles) {
40
+ (0, invariant_1.default)((0, utils_1.isString)(entry), 'wepback entry must be a string');
41
+ virtualContent.push(`import('${entry}');`);
42
+ }
43
+ virtualModules[virtualPath] = virtualContent.join('\n');
44
+ asyncEntry[key] = virtualPath;
45
+ }
46
+ return {
47
+ asyncEntry,
48
+ virtualModules
49
+ };
50
+ }
27
51
  class DynamicDll {
28
52
  constructor(opts) {
29
53
  this._hasBuilt = false;
@@ -79,7 +103,7 @@ class DynamicDll {
79
103
  acc[name] = entries[name].values();
80
104
  return acc;
81
105
  }, {});
82
- const { asyncEntry, virtualModules } = this._makeAsyncEntry(entry);
106
+ const { asyncEntry, virtualModules } = makeAsyncEntry(entry);
83
107
  chain.entryPoints.clear();
84
108
  chain.merge({
85
109
  entry: asyncEntry
@@ -94,7 +118,7 @@ class DynamicDll {
94
118
  return chain;
95
119
  };
96
120
  this.modifyWebpack = (config) => {
97
- const { asyncEntry, virtualModules } = this._makeAsyncEntry(config.entry);
121
+ const { asyncEntry, virtualModules } = makeAsyncEntry(config.entry);
98
122
  config.entry = asyncEntry;
99
123
  const webpack = this._resolveWebpackModule('webpack');
100
124
  if (!config.plugins) {
@@ -135,30 +159,6 @@ class DynamicDll {
135
159
  });
136
160
  });
137
161
  }
138
- _makeAsyncEntry(entry) {
139
- const asyncEntry = {};
140
- const virtualModules = {};
141
- const entryObject = ((0, utils_1.isString)(entry) || (0, utils_1.isArray)(entry)
142
- ? { main: [].concat(entry) }
143
- : entry);
144
- for (const key of Object.keys(entryObject)) {
145
- const virtualPath = `./dynamic-dll-virtual-entry/${key}.js`;
146
- const virtualContent = [];
147
- const entryFiles = (0, utils_1.isArray)(entryObject[key])
148
- ? entryObject[key]
149
- : [entryObject[key]];
150
- for (let entry of entryFiles) {
151
- (0, invariant_1.default)((0, utils_1.isString)(entry), 'wepback entry must be a string');
152
- virtualContent.push(`import('${entry}');`);
153
- }
154
- virtualModules[virtualPath] = virtualContent.join('\n');
155
- asyncEntry[key] = virtualPath;
156
- }
157
- return {
158
- asyncEntry,
159
- virtualModules
160
- };
161
- }
162
162
  _getMFconfig() {
163
163
  return {
164
164
  name: '__',
@@ -2,7 +2,6 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DynamicDLLPlugin = void 0;
4
4
  const moduleCollector_1 = require("../moduleCollector");
5
- // todo:
6
5
  const PLUGIN_NAME = 'DLLBuildDeps';
7
6
  class DynamicDLLPlugin {
8
7
  constructor(opts) {
@@ -1,7 +1,5 @@
1
1
  import webpack from 'webpack';
2
2
  export { webpack as default };
3
- import WebpackDevMiddleware from 'webpack-dev-middleware';
4
- export { WebpackDevMiddleware };
5
3
  export { WebpackChain } from './config';
6
4
  export { DynamicDll } from './dynamic-dll';
7
5
  /**
@@ -9,9 +7,9 @@ export { DynamicDll } from './dynamic-dll';
9
7
  */
10
8
  export { webpack, validate, validateSchema, version, cli, ModuleFilenameHelpers, RuntimeGlobals, UsageState, WebpackOptionsValidationError, ValidationError, cache, config, dependencies, ids, javascript, optimize, runtime, prefetch, web, webworker, node, electron, wasm, library, container, sharing, debug, util, sources, experiments, WebpackPluginFunction,
11
9
  /** export */
12
- AutomaticPrefetchPlugin, AsyncDependenciesBlock, BannerPlugin, Cache, Chunk, ChunkGraph, CleanPlugin, Compilation, Compiler, ConcatenationScope, ContextExclusionPlugin, ContextReplacementPlugin, DefinePlugin, DelegatedPlugin, Dependency, DllPlugin, DllReferencePlugin, DynamicEntryPlugin, EntryOptionPlugin, EntryPlugin, EnvironmentPlugin, EvalDevToolModulePlugin, EvalSourceMapDevToolPlugin, ExternalModule, ExternalsPlugin, Generator, HotUpdateChunk, HotModuleReplacementPlugin, IgnorePlugin, JavascriptModulesPlugin, LibManifestPlugin, LibraryTemplatePlugin, LoaderOptionsPlugin, LoaderTargetPlugin, Module, ModuleGraph, ModuleGraphConnection, NoEmitOnErrorsPlugin, NormalModule, NormalModuleReplacementPlugin, MultiCompiler, Parser, PrefetchPlugin, ProgressPlugin, ProvidePlugin, RuntimeModule, EntryPlugin as SingleEntryPlugin, SourceMapDevToolPlugin, Stats, Template, WatchIgnorePlugin, WebpackError, WebpackOptionsApply, WebpackOptionsDefaulter, Entry, EntryNormalized, EntryObject, LibraryOptions, ModuleOptions, ResolveOptions, RuleSetCondition, RuleSetConditionAbsolute, RuleSetRule, RuleSetUse, RuleSetUseItem, Configuration, WebpackOptionsNormalized, WebpackPluginInstance, Asset, AssetInfo, MultiStats, ParserState, Watching, StatsAsset, StatsChunk, StatsChunkGroup, StatsChunkOrigin, StatsCompilation, StatsError, StatsLogging, StatsLoggingEntry, StatsModule, StatsModuleIssuer, StatsModuleReason, StatsModuleTraceDependency, StatsModuleTraceItem, StatsProfile } from 'webpack';
10
+ AutomaticPrefetchPlugin, AsyncDependenciesBlock, BannerPlugin, Cache, Chunk, ChunkGraph, CleanPlugin, Compilation, Compiler, ConcatenationScope, ContextExclusionPlugin, ContextReplacementPlugin, DefinePlugin, DelegatedPlugin, Dependency, DllPlugin, DllReferencePlugin, DynamicEntryPlugin, EntryOptionPlugin, EntryPlugin, EnvironmentPlugin, EvalDevToolModulePlugin, EvalSourceMapDevToolPlugin, ExternalModule, ExternalsPlugin, Generator, HotUpdateChunk, HotModuleReplacementPlugin, IgnorePlugin, JavascriptModulesPlugin, LibManifestPlugin, LibraryTemplatePlugin, LoaderOptionsPlugin, LoaderTargetPlugin, Module, ModuleGraph, ModuleGraphConnection, NoEmitOnErrorsPlugin, NormalModule, NormalModuleReplacementPlugin, MultiCompiler, Parser, Plugin, PrefetchPlugin, ProgressPlugin, ProvidePlugin, RuntimeModule, EntryPlugin as SingleEntryPlugin, SourceMapDevToolPlugin, Stats, Template, WatchIgnorePlugin, WebpackError, WebpackOptionsApply, WebpackOptionsDefaulter, Entry, EntryNormalized, EntryObject, LibraryOptions, ModuleOptions, ResolveOptions, RuleSetCondition, RuleSetConditionAbsolute, RuleSetRule, RuleSetUse, RuleSetUseItem, Configuration, WebpackOptionsNormalized, WebpackPluginInstance, Asset, AssetInfo, MultiStats, ParserState, Watching, StatsAsset, StatsChunk, StatsChunkGroup, StatsChunkOrigin, StatsCompilation, StatsError, StatsLogging, StatsLoggingEntry, StatsModule, StatsModuleIssuer, StatsModuleReason, StatsModuleTraceDependency, StatsModuleTraceItem, StatsProfile } from 'webpack';
13
11
  /**
14
12
  * resolve webpack module for not shuvi plugin
15
13
  */
16
- declare const webpackPath: string;
17
- export { webpackPath };
14
+ declare const webpackResolveContext: string;
15
+ export { webpackResolveContext };