@shuvi/toolpack 1.0.63 → 2.0.0-dev.6

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 (55) hide show
  1. package/lib/utils/tsCheckerRspackPlugin.d.ts +4 -0
  2. package/lib/utils/tsCheckerRspackPlugin.js +7 -0
  3. package/lib/webpack/config/base.rspack.d.ts +35 -0
  4. package/lib/webpack/config/base.rspack.js +329 -0
  5. package/lib/webpack/config/browser.rspack.d.ts +3 -0
  6. package/lib/webpack/config/browser.rspack.js +228 -0
  7. package/lib/webpack/config/{browser.d.ts → browser.webpack.d.ts} +1 -1
  8. package/lib/webpack/config/{browser.js → browser.webpack.js} +11 -11
  9. package/lib/webpack/config/index.d.ts +4 -4
  10. package/lib/webpack/config/index.js +4 -4
  11. package/lib/webpack/config/index.webpack.d.ts +4 -0
  12. package/lib/webpack/config/index.webpack.js +20 -0
  13. package/lib/webpack/config/node.rspack.d.ts +2 -0
  14. package/lib/webpack/config/node.rspack.js +52 -0
  15. package/lib/webpack/config/{node.d.ts → node.webpack.d.ts} +1 -1
  16. package/lib/webpack/config/{node.js → node.webpack.js} +7 -7
  17. package/lib/webpack/config/parts/external.d.ts +1 -1
  18. package/lib/webpack/config/parts/helpers.rspack.d.ts +49 -0
  19. package/lib/webpack/config/parts/helpers.rspack.js +106 -0
  20. package/lib/webpack/config/parts/{helpers.d.ts → helpers.webpack.d.ts} +2 -2
  21. package/lib/webpack/config/parts/{style.d.ts → style.rspack.d.ts} +1 -1
  22. package/lib/webpack/config/parts/style.rspack.js +294 -0
  23. package/lib/webpack/config/parts/style.webpack.d.ts +12 -0
  24. package/lib/webpack/config/parts/{style.js → style.webpack.js} +2 -2
  25. package/lib/webpack/dynamic-dll/dep/getModuleExports.d.ts +1 -1
  26. package/lib/webpack/index.d.ts +5 -3
  27. package/lib/webpack/index.js +13 -8
  28. package/lib/webpack/index.webpack.d.ts +5 -0
  29. package/lib/webpack/index.webpack.js +29 -0
  30. package/lib/webpack/plugins/chunk-names-plugin.d.ts +3 -0
  31. package/lib/webpack/plugins/chunk-names-plugin.js +3 -0
  32. package/lib/webpack/plugins/copy-file-plugin.rspack.d.ts +14 -0
  33. package/lib/webpack/plugins/copy-file-plugin.rspack.js +88 -0
  34. package/lib/webpack/plugins/module-replace-plugin/dynamic-loader-options-hack.d.ts +8 -0
  35. package/lib/webpack/plugins/module-replace-plugin/dynamic-loader-options-hack.js +16 -0
  36. package/lib/webpack/plugins/module-replace-plugin/plugin.rspack.d.ts +38 -0
  37. package/lib/webpack/plugins/module-replace-plugin/plugin.rspack.js +224 -0
  38. package/lib/webpack/plugins/module-replace-plugin/stub-loader.d.ts +26 -0
  39. package/lib/webpack/plugins/module-replace-plugin/stub-loader.js +47 -1
  40. package/lib/webpack/plugins/module-replace-plugin/stub-loader.rspack.d.ts +31 -0
  41. package/lib/webpack/plugins/module-replace-plugin/stub-loader.rspack.js +89 -0
  42. package/lib/webpack/plugins/require-cache-hot-reloader-plugin.rspack.d.ts +13 -0
  43. package/lib/webpack/plugins/require-cache-hot-reloader-plugin.rspack.js +47 -0
  44. package/lib/webpack/rspack.d.ts +197 -0
  45. package/lib/webpack/rspack.js +192 -0
  46. package/lib/webpack/types.rspack.d.ts +45 -0
  47. package/lib/webpack/{types.d.ts → types.webpack.d.ts} +1 -1
  48. package/lib/webpack/types.webpack.js +2 -0
  49. package/lib/webpack/webpack.d.ts +1 -1
  50. package/lib/webpack/webpack.js +2 -2
  51. package/package.json +10 -5
  52. /package/lib/webpack/config/{base.d.ts → base.webpack.d.ts} +0 -0
  53. /package/lib/webpack/config/{base.js → base.webpack.js} +0 -0
  54. /package/lib/webpack/config/parts/{helpers.js → helpers.webpack.js} +0 -0
  55. /package/lib/webpack/{types.js → types.rspack.js} +0 -0
@@ -0,0 +1,4 @@
1
+ import { TsCheckerRspackPlugin } from 'ts-checker-rspack-plugin';
2
+ export { Issue } from 'ts-checker-rspack-plugin/lib/issue';
3
+ export { createCodeFrameFormatter } from 'ts-checker-rspack-plugin/lib/formatter';
4
+ export default TsCheckerRspackPlugin;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createCodeFrameFormatter = void 0;
4
+ const ts_checker_rspack_plugin_1 = require("ts-checker-rspack-plugin");
5
+ var formatter_1 = require("ts-checker-rspack-plugin/lib/formatter");
6
+ Object.defineProperty(exports, "createCodeFrameFormatter", { enumerable: true, get: function () { return formatter_1.createCodeFrameFormatter; } });
7
+ exports.default = ts_checker_rspack_plugin_1.TsCheckerRspackPlugin;
@@ -0,0 +1,35 @@
1
+ import RspackChain from 'rspack-chain';
2
+ import { CompilerOptions } from '../loaders/shuvi-swc-loader';
3
+ type TsCompilerOptions = import('typescript').CompilerOptions;
4
+ export interface BaseOptions {
5
+ dev: boolean;
6
+ name: string;
7
+ projectRoot: string;
8
+ outputDir: string;
9
+ cacheDir: string;
10
+ include: (string | RegExp)[];
11
+ jsConfig?: {
12
+ useTypeScript: boolean;
13
+ typeScriptPath?: string;
14
+ compilerOptions: TsCompilerOptions;
15
+ resolvedBaseUrl: string;
16
+ };
17
+ target?: string;
18
+ publicPath?: string;
19
+ env?: {
20
+ [x: string]: string | undefined;
21
+ };
22
+ lightningCss?: boolean;
23
+ compiler?: CompilerOptions;
24
+ analyze?: boolean;
25
+ }
26
+ /**
27
+ * @unsupported Rspack does not support TerserPlugin or CssMinimizerPlugin directly.
28
+ */
29
+ export { RspackChain };
30
+ export declare function getDefineEnv(env: {
31
+ [x: string]: string | undefined;
32
+ }): {
33
+ [x: string]: string;
34
+ };
35
+ export declare function baseRspackChain({ dev, outputDir, lightningCss, compiler, projectRoot, include, jsConfig, name, publicPath, env, cacheDir, analyze }: BaseOptions): RspackChain;
@@ -0,0 +1,329 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.RspackChain = void 0;
30
+ exports.getDefineEnv = getDefineEnv;
31
+ exports.baseRspackChain = baseRspackChain;
32
+ const rspack_chain_1 = __importDefault(require("rspack-chain"));
33
+ exports.RspackChain = rspack_chain_1.default;
34
+ const webpack_bundle_analyzer_1 = require("webpack-bundle-analyzer");
35
+ /**
36
+ * @unsupported Rspack does not support TerserPlugin or CssMinimizerPlugin directly.
37
+ * TODO: Use Rspack's built-in minification or custom plugin when available.
38
+ */
39
+ // import TerserPlugin from 'terser-webpack-plugin';
40
+ // import CssMinimizerPlugin from 'css-minimizer-webpack-plugin';
41
+ const rspack = __importStar(require("@rspack/core"));
42
+ const path = __importStar(require("path"));
43
+ const fs = __importStar(require("fs"));
44
+ const constants_1 = require("@shuvi/shared/constants");
45
+ const fix_watching_plugin_1 = __importDefault(require("../plugins/fix-watching-plugin"));
46
+ const resolveLocalLoader = (name) => path.join(__dirname, `../loaders/${name}`);
47
+ function getDefineEnv(env) {
48
+ return Object.assign(Object.assign({}, Object.keys(process.env).reduce((prev, key) => {
49
+ if (key.startsWith(constants_1.PUBLIC_ENV_PREFIX)) {
50
+ prev[`process.env.${key}`] = JSON.stringify(process.env[key]);
51
+ }
52
+ return prev;
53
+ }, {})), Object.keys(env).reduce((acc, key) => {
54
+ if (/^(?:NODE_.+)|^(?:__.+)$/i.test(key)) {
55
+ throw new Error(`The key "${key}" under "env" is not allowed.`);
56
+ }
57
+ return Object.assign(Object.assign({}, acc), { [`process.env.${key}`]: JSON.stringify(env[key]) });
58
+ }, {}));
59
+ }
60
+ /** remove 'shuvi/' of the target name */
61
+ const getSimplifiedTargetName = (targetName) => targetName.replace(/^shuvi\//, '');
62
+ function baseRspackChain({ dev, outputDir, lightningCss, compiler, projectRoot, include, jsConfig, name, publicPath = '/', env = {}, cacheDir, analyze }) {
63
+ const config = new rspack_chain_1.default();
64
+ config.mode(dev ? 'development' : 'production');
65
+ config.bail(!dev);
66
+ config.performance.hints(false);
67
+ config.context(projectRoot);
68
+ config.devtool(dev ? 'eval' : false);
69
+ config.output.path(outputDir);
70
+ config.output.merge({
71
+ publicPath,
72
+ filename: `${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
73
+ // This saves chunks with the name given via `import()`
74
+ chunkFilename: `static/chunks/${dev ? '[name]' : '[name].[contenthash:8]'}.js`,
75
+ hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js',
76
+ hotUpdateMainFilename: 'static/webpack/[runtime].[fullhash].hot-update.json',
77
+ strictModuleExceptionHandling: true,
78
+ // crossOriginLoading: crossOrigin,
79
+ webassemblyModuleFilename: 'static/wasm/[modulehash:8].wasm',
80
+ hashFunction: 'xxhash64',
81
+ hashDigestLength: 16
82
+ });
83
+ config.optimization.merge({
84
+ emitOnErrors: !dev,
85
+ /**
86
+ * The following options are not currently supported by Rspack:
87
+ *
88
+ * - checkWasmTypes: Ensures WebAssembly modules have correct types. Rspack does not expose this option (see https://github.com/web-infra-dev/rspack/issues/ for updates).
89
+ * - nodeEnv: Allows overriding process.env.NODE_ENV for modules. Rspack sets this automatically based on mode and does not allow manual override.
90
+ * - realContentHash: Ensures content hash is based on the real content. Rspack does not expose this option; its hashing is internal and may differ from Webpack.
91
+ *
92
+ * @todo If Rspack exposes these options in the future, restore them for full parity.
93
+ */
94
+ // checkWasmTypes: false,
95
+ // nodeEnv: false,
96
+ runtimeChunk: undefined,
97
+ minimize: !dev
98
+ // realContentHash: false
99
+ });
100
+ if (dev) {
101
+ config.optimization.usedExports(false);
102
+ }
103
+ else {
104
+ /**
105
+ * @todo Rspack does not support TerserPlugin or CssMinimizerPlugin directly.
106
+ *
107
+ * - TerserPlugin: Used in Webpack for advanced JS minification. Rspack has built-in minification, but does not allow custom minimizer plugins yet.
108
+ * - CssMinimizerPlugin: Used for CSS minification. Rspack's CSS minification is built-in and not pluggable as of now.
109
+ *
110
+ * Migration advice: Monitor Rspack's plugin API and minimizer support. If/when Rspack allows custom minimizers, these can be restored for advanced/custom minification needs.
111
+ * See: https://rspack.dev/guide/plugin.html and https://github.com/web-infra-dev/rspack/issues/ for updates.
112
+ */
113
+ // config.optimization.minimizer('terser').use(TerserPlugin, [ ... ]);
114
+ // config.optimization.minimizer('cssMinimizer').use(CssMinimizerPlugin, [ ... ]);
115
+ if (analyze) {
116
+ const targetName = getSimplifiedTargetName(name);
117
+ config
118
+ .plugin('private/bundle-analyzer-plugin')
119
+ .use(webpack_bundle_analyzer_1.BundleAnalyzerPlugin, [
120
+ {
121
+ logLevel: 'warn',
122
+ openAnalyzer: false,
123
+ analyzerMode: 'static',
124
+ reportFilename: `../analyze/${targetName}.html`,
125
+ generateStatsFile: true,
126
+ statsFilename: `../analyze/${targetName}-stats.json`
127
+ }
128
+ ]);
129
+ }
130
+ }
131
+ // Support for NODE_PATH
132
+ const nodePathList = (process.env.NODE_PATH || '')
133
+ .split(process.platform === 'win32' ? ';' : ':')
134
+ .filter(p => !!p);
135
+ config.resolve.merge({
136
+ modules: [
137
+ 'node_modules',
138
+ ...nodePathList // Support for NODE_PATH environment variable
139
+ ]
140
+ });
141
+ config.resolve.alias.set('@swc/helpers', path.dirname(require.resolve(`@swc/helpers/package.json`)));
142
+ config.resolveLoader.merge({
143
+ alias: [
144
+ 'lightningcss-loader',
145
+ 'shuvi-swc-loader',
146
+ 'empty-loader',
147
+ 'route-component-loader'
148
+ ].reduce((alias, loader) => {
149
+ alias[`@shuvi/${loader}`] = resolveLocalLoader(loader);
150
+ return alias;
151
+ }, {})
152
+ });
153
+ /**
154
+ * @unsupported Rspack does not support strictExportPresence.
155
+ * - Unrecognized key(s) in object: 'strictExportPresence' at "module"
156
+ */
157
+ // config.module.set('strictExportPresence', true);
158
+ const mainRule = config.module.rule('main');
159
+ // TODO: FIXME: await babel/babel-loader to update to fix this.
160
+ // x-ref: https://github.com/webpack/webpack/issues/11467
161
+ config.module
162
+ .rule('webpackPatch')
163
+ .test(/\.m?js/)
164
+ .resolve.set('fullySpecified', false);
165
+ config.module
166
+ .rule('private/shuvi-runtime')
167
+ .test(/\.shuvi[/\\]app[/\\]runtime[/\\]index\.(js|ts)/)
168
+ .set('sideEffects', false);
169
+ mainRule
170
+ .oneOf('js')
171
+ .test(/\.(tsx|ts|js|cjs|mjs|jsx)$/)
172
+ .include.merge([...include])
173
+ .end()
174
+ .use('shuvi-swc-loader')
175
+ /**
176
+ * @todo use builtin:swc-loader instead of shuvi-swc-loader
177
+ */
178
+ .loader('@shuvi/shuvi-swc-loader')
179
+ .options({
180
+ isServer: false,
181
+ compiler,
182
+ supportedBrowsers: false,
183
+ swcCacheDir: path.join(cacheDir, 'swc')
184
+ });
185
+ mainRule
186
+ .oneOf('media')
187
+ .exclude.merge([/\.(tsx|ts|js|cjs|mjs|jsx)$/, /\.html$/, /\.json$/])
188
+ .end()
189
+ // @ts-ignore
190
+ .type('asset/resource')
191
+ .set('generator', {
192
+ filename: (pathData) => {
193
+ // Check if a string is a base64 data URI
194
+ if (pathData.filename && isValidBase64DataURL(pathData.filename)) {
195
+ // Handle base64 string case, [name] is empty
196
+ return `static/media/base64.[hash:8][ext]`;
197
+ }
198
+ else {
199
+ return `static/media/[name].[hash:8][ext]`;
200
+ }
201
+ }
202
+ });
203
+ // .use('file-loader')
204
+ // .loader(require.resolve('file-loader'))
205
+ // .options({
206
+ // name: 'static/media/[name].[hash:8].[ext]'
207
+ // });
208
+ config.plugin('private/ignore-plugin').use(rspack.IgnorePlugin, [
209
+ {
210
+ resourceRegExp: /^\.\/locale$/,
211
+ contextRegExp: /moment$/
212
+ }
213
+ ]);
214
+ config.plugin('private/define').use(rspack.DefinePlugin, [
215
+ Object.assign({
216
+ // internal field to identify the plugin config
217
+ __SHUVI_DEFINE_ENV: 'true' }, getDefineEnv(env))
218
+ ]);
219
+ config.plugin('define').use(rspack.DefinePlugin, [
220
+ {
221
+ 'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
222
+ }
223
+ ]);
224
+ // const getCacheConfig = () => {
225
+ // const projectHash = crypto
226
+ // .createHash('md5')
227
+ // .update(projectRoot)
228
+ // .digest('hex');
229
+ // const stringifiedEnvs = Object.entries({
230
+ // ...getDefineEnv(env)
231
+ // }).reduce((prev: string, [key, value]) => {
232
+ // return `${prev}|${key}=${value}`;
233
+ // }, '');
234
+ // const PACKAGE_JSON = path.resolve(__dirname, '../../../package.json');
235
+ // const SHUVI_VERSION = require(PACKAGE_JSON).version;
236
+ // return {
237
+ // cacheDirectory: path.join(cacheDir, 'webpack', projectHash),
238
+ // type: 'filesystem',
239
+ // name: `${name.replace(/\//, '-')}-${config.get('mode')}`,
240
+ // version: `${SHUVI_VERSION}|${stringifiedEnvs}`
241
+ // };
242
+ // };
243
+ /**
244
+ * @unsupported Rspack only supports `cache: boolean`. Object cache config is not supported.
245
+ * See: https://rspack.dev/config/cache
246
+ */
247
+ // config.cache(
248
+ // typeof process.env.SHUVI_DEV_DISABLE_CACHE !== 'undefined'
249
+ // ? false
250
+ // : getCacheConfig()
251
+ // );
252
+ config.cache(typeof process.env.SHUVI_DEV_DISABLE_CACHE !== 'undefined' ? false : true);
253
+ const tsConfigPath = path.join(projectRoot, 'tsconfig.json');
254
+ const jsConfigPath = path.join(projectRoot, 'jsconfig.json');
255
+ if (jsConfig === null || jsConfig === void 0 ? void 0 : jsConfig.useTypeScript) {
256
+ if (fs.existsSync(tsConfigPath)) {
257
+ config.resolve.tsConfig(tsConfigPath);
258
+ }
259
+ }
260
+ else if (fs.existsSync(jsConfigPath)) {
261
+ config.resolve.tsConfig(jsConfigPath);
262
+ }
263
+ if (dev) {
264
+ // For rspack-dev-middleware usage
265
+ config.watchOptions({
266
+ aggregateTimeout: 5,
267
+ ignored: ['**/.git/**']
268
+ });
269
+ config.set('infrastructureLogging', {
270
+ level: 'none'
271
+ });
272
+ config.plugin('private/fix-watching-plugin').use(fix_watching_plugin_1.default);
273
+ }
274
+ else {
275
+ // class PrintModuleIdsPlugin {
276
+ // apply(compiler: rspack.Compiler) {
277
+ // compiler.hooks.compilation.tap('PrintModuleIdsPlugin', (compilation) => {
278
+ // compilation.hooks.processAssets.tap(
279
+ // {
280
+ // name: 'PrintModuleIdsPlugin',
281
+ // // PROCESS_ASSETS_STAGE_ADDITIONS 是比較晚的階段,ID 通常已分配完成
282
+ // stage: rspack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
283
+ // },
284
+ // () => {
285
+ // for (const module of compilation.modules) {
286
+ // const id = compilation.chunkGraph.getModuleId(module);
287
+ // if (id != null) {
288
+ // console.log('module id:', id, 'request:', (module as any).rawRequest || (module as any).userRequest);
289
+ // } else {
290
+ // console.log('module id: <null>', 'request:', (module as any).rawRequest || (module as any).userRequest);
291
+ // }
292
+ // }
293
+ // }
294
+ // );
295
+ // });
296
+ // }
297
+ // }
298
+ // config.plugin('private/print-module-ids-plugin').use(PrintModuleIdsPlugin);
299
+ /**
300
+ * enable deterministic module ids
301
+ * this is equivalent to webpack's HashedModuleIdsPlugin
302
+ */
303
+ config.optimization.merge({
304
+ moduleIds: 'deterministic' // equivalent to webpack's HashedModuleIdsPlugin
305
+ });
306
+ }
307
+ return config;
308
+ }
309
+ function isValidBase64DataURL(input) {
310
+ // Check if input starts with the data URI scheme
311
+ if (!input.startsWith('data:')) {
312
+ return false;
313
+ }
314
+ // Split the data URI into metadata and data parts
315
+ const parts = input.split(',');
316
+ if (parts.length !== 2) {
317
+ return false;
318
+ }
319
+ const metadata = parts[0];
320
+ const data = parts[1];
321
+ // Check if the metadata contains 'base64'
322
+ if (!metadata.includes('base64')) {
323
+ return false;
324
+ }
325
+ // Regular expression to validate Base64 string
326
+ const base64Regex = /^[A-Za-z0-9+/]+[=]{0,2}$/;
327
+ // Validate Base64 data
328
+ return base64Regex.test(data);
329
+ }
@@ -0,0 +1,3 @@
1
+ import { BaseOptions } from './base.rspack';
2
+ import RspackChain from 'rspack-chain';
3
+ export declare function createBrowserRspackChain(options: BaseOptions): RspackChain;
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.createBrowserRspackChain = createBrowserRspackChain;
27
+ const crypto = __importStar(require("crypto"));
28
+ const rspack = __importStar(require("@rspack/core"));
29
+ const path = __importStar(require("path"));
30
+ const resolve_1 = require("@shuvi/utils/resolve");
31
+ const base_rspack_1 = require("./base.rspack");
32
+ const style_rspack_1 = require("./parts/style.rspack");
33
+ const helpers_rspack_1 = require("./parts/helpers.rspack");
34
+ const ts_checker_rspack_plugin_1 = require("ts-checker-rspack-plugin");
35
+ const BIG_LIBRARY_THRESHOLD = 160000; // byte
36
+ const SHUVI_PKGS_REGEX = /[\\/]node_modules[\\/](@shuvi|doura)[\\/]/;
37
+ const FRAMEWORK_REACT_MODULES = [
38
+ {
39
+ test: /[/\\]node_modules[/\\]react[/\\]/
40
+ },
41
+ {
42
+ test: /[/\\]node_modules[/\\]react-dom[/\\]/
43
+ },
44
+ {
45
+ test: /[/\\]node_modules[/\\]scheduler[/\\]/,
46
+ issuers: [/[/\\]node_modules[/\\]react-dom[/\\]/]
47
+ }
48
+ ];
49
+ function createBrowserRspackChain(options) {
50
+ const { projectRoot: projectRoot, cacheDir: cacheDir, jsConfig, dev, publicPath } = options;
51
+ const chain = (0, base_rspack_1.baseRspackChain)(options);
52
+ const useTypeScript = !!(jsConfig === null || jsConfig === void 0 ? void 0 : jsConfig.useTypeScript);
53
+ chain.target('web');
54
+ chain.devtool(dev ? 'cheap-module-source-map' : false);
55
+ chain.resolve.extensions.merge([
56
+ '.ts',
57
+ '.tsx',
58
+ '.mjs',
59
+ '.js',
60
+ '.jsx',
61
+ '.json',
62
+ '.wasm'
63
+ ]);
64
+ if (useTypeScript) {
65
+ chain
66
+ .plugin('private/ts-checker-rspack-plugin')
67
+ .use(ts_checker_rspack_plugin_1.TsCheckerRspackPlugin, [
68
+ {
69
+ typescript: {
70
+ configFile: path.join(projectRoot, 'tsconfig.json'),
71
+ mode: 'write-references',
72
+ typescriptPath: jsConfig.typeScriptPath,
73
+ diagnosticOptions: {
74
+ syntactic: true
75
+ },
76
+ configOverwrite: {
77
+ compilerOptions: {
78
+ incremental: true,
79
+ tsBuildInfoFile: path.resolve(cacheDir, 'tsbuildinfo')
80
+ }
81
+ }
82
+ },
83
+ async: dev,
84
+ logger: {
85
+ log: message => console.log(message),
86
+ error: message => console.error(message)
87
+ },
88
+ formatter: 'codeframe'
89
+ }
90
+ ]);
91
+ }
92
+ if (dev) {
93
+ chain.plugin('private/hmr-plugin').use(rspack.HotModuleReplacementPlugin);
94
+ // disable splitChunks at dev mode to prevent preload error
95
+ chain.optimization.splitChunks(false);
96
+ }
97
+ else {
98
+ const getDefaultChunkName = (_module, chunks) => {
99
+ return crypto
100
+ .createHash('sha1')
101
+ .update(chunks.reduce((acc, chunk) => {
102
+ return acc + chunk.name;
103
+ }, ''))
104
+ .digest('hex')
105
+ .substring(0, 8);
106
+ };
107
+ chain.optimization.splitChunks({
108
+ chunks: helpers_rspack_1.splitChunksFilter,
109
+ cacheGroups: {
110
+ default: Object.assign({ name: getDefaultChunkName, filename: (0, helpers_rspack_1.commonChunkFilename)({ dev: false }) }, helpers_rspack_1.defaultCacheGroups.default),
111
+ defaultVendors: Object.assign({ name: getDefaultChunkName, filename: (0, helpers_rspack_1.commonChunkFilename)({ dev: false }) }, helpers_rspack_1.defaultCacheGroups.defaultVendors),
112
+ framework: {
113
+ chunks: 'all',
114
+ name: 'framework',
115
+ filename: (0, helpers_rspack_1.commonChunkFilename)({ dev: false }),
116
+ test(module, { moduleGraph }) {
117
+ const resource = module.nameForCondition();
118
+ if (!resource) {
119
+ return false;
120
+ }
121
+ if (SHUVI_PKGS_REGEX.test(resource)) {
122
+ return true;
123
+ }
124
+ return FRAMEWORK_REACT_MODULES.some(frameworkModule => {
125
+ if (!frameworkModule.test.test(resource)) {
126
+ return false;
127
+ }
128
+ // Check issuer to ignore nested copies of framework libraries so they're
129
+ // bundled with their issuer.
130
+ // https://github.com/zeit/next.js/pull/9012
131
+ if (frameworkModule.issuers) {
132
+ for (const issuerTest of frameworkModule.issuers) {
133
+ // fix: DeprecationWarning: Module.issuer: Use new ModuleGraph API
134
+ const issuer = moduleGraph.getIssuer(module);
135
+ const issuerResource = issuer
136
+ ? issuer.nameForCondition()
137
+ : null;
138
+ if (!issuerResource || !issuerTest.test(issuerResource)) {
139
+ return false;
140
+ }
141
+ }
142
+ }
143
+ return true;
144
+ });
145
+ },
146
+ // test: /(?<!node_modules.*)[\\/]node_modules[\\/](react|react-dom|@shuvi[\\/]router|@shuvi[\\/]router-react|scheduler|prop-types|use-sync-external-store|history)[\\/]/,
147
+ priority: 40,
148
+ // Don't let webpack eliminate this chunk (prevents this chunk from
149
+ // becoming a part of the commons chunk)
150
+ enforce: true
151
+ },
152
+ lib: {
153
+ test(module) {
154
+ return (module.size() > BIG_LIBRARY_THRESHOLD &&
155
+ helpers_rspack_1.NODE_MODULES_REGEXP.test(module.nameForCondition() || ''));
156
+ },
157
+ /**
158
+ * @unsupported Rspack does not support libIdent directly.
159
+ */
160
+ // name(module: {
161
+ // type: string;
162
+ // libIdent?: Function;
163
+ // updateHash: (hash: crypto.Hash) => void;
164
+ // }): string {
165
+ // const hash = crypto.createHash('sha1');
166
+ // if (module.type === `css/mini-extract`) {
167
+ // module.updateHash(hash);
168
+ // } else {
169
+ // if (!module.libIdent) {
170
+ // throw new Error(
171
+ // `Encountered unknown module type: ${module.type}. Please open an issue.`
172
+ // );
173
+ // }
174
+ // hash.update(module.libIdent({ context: options.projectRoot }));
175
+ // }
176
+ // return hash.digest('hex').substring(0, 8);
177
+ // },
178
+ name: 'lib',
179
+ filename: (0, helpers_rspack_1.commonChunkFilename)({ dev: false }),
180
+ priority: 30,
181
+ minChunks: 1,
182
+ reuseExistingChunk: true
183
+ }
184
+ },
185
+ maxInitialRequests: 25,
186
+ minSize: 20000
187
+ });
188
+ }
189
+ // node polyfills
190
+ chain.resolve.fallback.merge({
191
+ buffer: (0, resolve_1.resolve)('buffer', {
192
+ includeCoreModules: false
193
+ }),
194
+ crypto: require.resolve('crypto-browserify'),
195
+ path: require.resolve('path-browserify'),
196
+ stream: require.resolve('stream-browserify'),
197
+ vm: require.resolve('vm-browserify')
198
+ });
199
+ chain.plugin('node-buffer-polyfill').use(rspack.ProvidePlugin, [
200
+ {
201
+ Buffer: ['buffer', 'Buffer']
202
+ }
203
+ ]);
204
+ chain.plugin('node-process-polyfill').use(rspack.ProvidePlugin, [
205
+ {
206
+ process: ['process']
207
+ }
208
+ ]);
209
+ chain.plugin('define').tap((args) => {
210
+ const [options = {}] = args;
211
+ return [
212
+ Object.assign(Object.assign({}, options), { __BROWSER__: true,
213
+ /**
214
+ * swc.optimizer can't handle `typeof window` correctly for dependencies
215
+ */
216
+ 'typeof window': JSON.stringify('object'),
217
+ // prevent errof of destructing process.env
218
+ 'process.env': JSON.stringify('{}') })
219
+ ];
220
+ });
221
+ return (0, style_rspack_1.withStyle)(chain, {
222
+ extractCss: !dev,
223
+ publicPath,
224
+ lightningCss: options.lightningCss,
225
+ filename: 'static/css/[contenthash:8].css',
226
+ chunkFilename: 'static/css/[contenthash:8].chunk.css'
227
+ });
228
+ }
@@ -1,2 +1,2 @@
1
- import { WebpackChain, BaseOptions } from './base';
1
+ import { WebpackChain, BaseOptions } from './base.webpack';
2
2
  export declare function createBrowserWebpackChain(options: BaseOptions): WebpackChain;