@rsbuild/plugin-react 0.0.0-next-20231115072032 → 0.0.0-next-20231207110454

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,14 @@
1
1
  import { RsbuildPlugin } from '@rsbuild/core';
2
2
 
3
- declare const pluginReact: () => RsbuildPlugin;
3
+ declare const isBeyondReact17: (cwd: string) => Promise<boolean>;
4
4
 
5
- export { pluginReact };
5
+ type SplitReactChunkOptions = {
6
+ react?: boolean;
7
+ router?: boolean;
8
+ };
9
+ type PluginReactOptions = {
10
+ splitChunks?: SplitReactChunkOptions;
11
+ };
12
+ declare const pluginReact: (options?: PluginReactOptions) => RsbuildPlugin;
13
+
14
+ export { PluginReactOptions, SplitReactChunkOptions, isBeyondReact17, pluginReact };
package/dist/index.js CHANGED
@@ -5,9 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __commonJS = (cb, mod) => function __require() {
9
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
- };
11
8
  var __export = (target, all) => {
12
9
  for (var name in all)
13
10
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -30,248 +27,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
27
  ));
31
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
29
 
33
- // ../core/dist/plugins/splitChunks.js
34
- var require_splitChunks = __commonJS({
35
- "../core/dist/plugins/splitChunks.js"(exports, module2) {
36
- "use strict";
37
- var __create2 = Object.create;
38
- var __defProp2 = Object.defineProperty;
39
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
40
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
41
- var __getProtoOf2 = Object.getPrototypeOf;
42
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
43
- var __export2 = (target, all) => {
44
- for (var name in all)
45
- __defProp2(target, name, { get: all[name], enumerable: true });
46
- };
47
- var __copyProps2 = (to, from, except, desc) => {
48
- if (from && typeof from === "object" || typeof from === "function") {
49
- for (let key of __getOwnPropNames2(from))
50
- if (!__hasOwnProp2.call(to, key) && key !== except)
51
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
52
- }
53
- return to;
54
- };
55
- var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
56
- // If the importer is in node compatibility mode or this is not an ESM
57
- // file that has been converted to a CommonJS file using a Babel-
58
- // compatible transform (i.e. "__esModule" has not been set), then set
59
- // "default" to the CommonJS "module.exports" for node compatibility.
60
- isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
61
- mod
62
- ));
63
- var __toCommonJS2 = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
64
- var splitChunks_exports = {};
65
- __export2(splitChunks_exports, {
66
- createDependenciesRegExp: () => createDependenciesRegExp2,
67
- pluginSplitChunks: () => pluginSplitChunks
68
- });
69
- module2.exports = __toCommonJS2(splitChunks_exports);
70
- var import_assert = __toESM2(require("assert"));
71
- var import_shared5 = require("@rsbuild/shared");
72
- function getUserDefinedCacheGroups(forceSplitting) {
73
- const cacheGroups = {};
74
- const pairs = Array.isArray(forceSplitting) ? forceSplitting.map(
75
- (regexp, index) => [`force-split-${index}`, regexp]
76
- ) : Object.entries(forceSplitting);
77
- pairs.forEach(([key, regexp]) => {
78
- cacheGroups[key] = {
79
- test: regexp,
80
- name: key,
81
- chunks: "all",
82
- // Ignore minimum size, minimum chunks and maximum requests and always create chunks for user defined cache group.
83
- enforce: true
84
- };
85
- });
86
- return cacheGroups;
87
- }
88
- var DEPENDENCY_MATCH_TEMPL = /[\\/]node_modules[\\/](<SOURCES>)[\\/]/.source;
89
- var createDependenciesRegExp2 = (...dependencies) => {
90
- const sources = dependencies.map(
91
- (d) => typeof d === "string" ? d : d.source
92
- );
93
- const expr = DEPENDENCY_MATCH_TEMPL.replace("<SOURCES>", sources.join("|"));
94
- return new RegExp(expr);
95
- };
96
- function splitByExperience2(ctx) {
97
- const { override, polyfill, defaultConfig, userDefinedCacheGroups } = ctx;
98
- const experienceCacheGroup = {};
99
- const packageRegExps = {
100
- lodash: createDependenciesRegExp2("lodash", "lodash-es"),
101
- axios: createDependenciesRegExp2("axios", /axios-.+/)
102
- };
103
- if (polyfill === "entry" || polyfill === "usage") {
104
- packageRegExps.polyfill = createDependenciesRegExp2(
105
- "tslib",
106
- "core-js",
107
- "@babel/runtime",
108
- "@swc/helpers"
109
- );
110
- }
111
- Object.entries(packageRegExps).forEach(([name, test]) => {
112
- const key = `lib-${name}`;
113
- experienceCacheGroup[key] = {
114
- test,
115
- priority: 0,
116
- name: key,
117
- reuseExistingChunk: true
118
- };
119
- });
120
- return {
121
- ...defaultConfig,
122
- ...override,
123
- cacheGroups: {
124
- ...defaultConfig.cacheGroups,
125
- ...experienceCacheGroup,
126
- ...userDefinedCacheGroups,
127
- ...override.cacheGroups
128
- }
129
- };
130
- }
131
- function splitByModule(ctx) {
132
- const { override, userDefinedCacheGroups, defaultConfig } = ctx;
133
- return {
134
- ...defaultConfig,
135
- minSize: 0,
136
- maxInitialRequests: Infinity,
137
- ...override,
138
- cacheGroups: {
139
- ...defaultConfig.cacheGroups,
140
- ...userDefinedCacheGroups,
141
- // Core group
142
- vendors: {
143
- priority: -10,
144
- test: import_shared5.NODE_MODULES_REGEX,
145
- // todo: not support in rspack
146
- // @ts-expect-error
147
- name(module22) {
148
- return (0, import_shared5.getPackageNameFromModulePath)(module22.context);
149
- }
150
- },
151
- ...override.cacheGroups
152
- }
153
- };
154
- }
155
- function splitBySize(ctx) {
156
- var _a, _b;
157
- const { override, userDefinedCacheGroups, defaultConfig, rsbuildConfig } = ctx;
158
- (0, import_assert.default)(rsbuildConfig.strategy === "split-by-size");
159
- return {
160
- ...defaultConfig,
161
- minSize: (_a = rsbuildConfig.minSize) != null ? _a : 0,
162
- maxSize: (_b = rsbuildConfig.maxSize) != null ? _b : Infinity,
163
- ...override,
164
- cacheGroups: {
165
- ...defaultConfig.cacheGroups,
166
- ...userDefinedCacheGroups,
167
- ...override.cacheGroups
168
- }
169
- };
170
- }
171
- function splitCustom(ctx) {
172
- const { override, userDefinedCacheGroups, defaultConfig } = ctx;
173
- return {
174
- ...defaultConfig,
175
- ...override,
176
- cacheGroups: {
177
- ...defaultConfig.cacheGroups,
178
- ...userDefinedCacheGroups,
179
- ...override.cacheGroups
180
- }
181
- };
182
- }
183
- function allInOne(_ctx) {
184
- return false;
185
- }
186
- function singleVendor(ctx) {
187
- const { override, defaultConfig, userDefinedCacheGroups } = ctx;
188
- const singleVendorCacheGroup = {
189
- singleVendor: {
190
- test: import_shared5.NODE_MODULES_REGEX,
191
- priority: 0,
192
- chunks: "all",
193
- name: "vendor",
194
- enforce: true,
195
- reuseExistingChunk: true
196
- }
197
- };
198
- return {
199
- ...defaultConfig,
200
- ...override,
201
- cacheGroups: {
202
- ...defaultConfig.cacheGroups,
203
- ...singleVendorCacheGroup,
204
- ...userDefinedCacheGroups,
205
- ...override.cacheGroups
206
- }
207
- };
208
- }
209
- var SPLIT_STRATEGY_DISPATCHER = {
210
- "split-by-experience": splitByExperience2,
211
- "split-by-module": splitByModule,
212
- "split-by-size": splitBySize,
213
- custom: splitCustom,
214
- "all-in-one": allInOne,
215
- "single-vendor": singleVendor
216
- };
217
- function pluginSplitChunks() {
218
- return {
219
- name: "plugin-split-chunks",
220
- setup(api) {
221
- api.modifyBundlerChain(
222
- async (chain, { isServer, isWebWorker, isServiceWorker }) => {
223
- var _a;
224
- if (isServer || isWebWorker || isServiceWorker) {
225
- chain.optimization.splitChunks(false);
226
- if (isWebWorker || isServiceWorker) {
227
- chain.module.parser.merge({
228
- javascript: {
229
- dynamicImportMode: "eager"
230
- }
231
- });
232
- }
233
- return;
234
- }
235
- const config = api.getNormalizedConfig();
236
- const defaultConfig = {
237
- // Optimize both `initial` and `async` chunks
238
- chunks: "all",
239
- // When chunk size >= 50000 bytes, split it into separate chunk
240
- // @ts-expect-error Rspack type missing
241
- enforceSizeThreshold: 5e4,
242
- cacheGroups: {}
243
- };
244
- const { chunkSplit } = config.performance;
245
- let userDefinedCacheGroups = {};
246
- if (chunkSplit.forceSplitting) {
247
- userDefinedCacheGroups = getUserDefinedCacheGroups(
248
- chunkSplit.forceSplitting
249
- );
250
- }
251
- const override = chunkSplit.strategy === "custom" ? (
252
- // `chunkSplit.splitChunks` compat for Eden
253
- (_a = chunkSplit.splitChunks) != null ? _a : chunkSplit.override
254
- ) : chunkSplit.override;
255
- const splitChunksOptions = await SPLIT_STRATEGY_DISPATCHER[chunkSplit.strategy]({
256
- defaultConfig,
257
- override: override || {},
258
- userDefinedCacheGroups,
259
- rsbuildConfig: chunkSplit,
260
- rootPath: api.context.rootPath,
261
- polyfill: config.output.polyfill
262
- });
263
- chain.optimization.splitChunks(splitChunksOptions);
264
- }
265
- );
266
- }
267
- };
268
- }
269
- }
270
- });
271
-
272
30
  // src/index.ts
273
31
  var src_exports = {};
274
32
  __export(src_exports, {
33
+ isBeyondReact17: () => isBeyondReact17,
275
34
  pluginReact: () => pluginReact
276
35
  });
277
36
  module.exports = __toCommonJS(src_exports);
@@ -291,16 +50,15 @@ var getAntdMajorVersion = (appDirectory) => {
291
50
  };
292
51
  var applyAntdSupport = (api) => {
293
52
  api.modifyRsbuildConfig((rsbuildConfig) => {
294
- var _a, _b, _c;
295
- (_a = rsbuildConfig.source) != null ? _a : rsbuildConfig.source = {};
296
- if (rsbuildConfig.source.transformImport === false || ((_b = rsbuildConfig.source.transformImport) == null ? void 0 : _b.some(
53
+ rsbuildConfig.source ?? (rsbuildConfig.source = {});
54
+ if (rsbuildConfig.source.transformImport === false || rsbuildConfig.source.transformImport?.some(
297
55
  (item) => item.libraryName === "antd"
298
- ))) {
56
+ )) {
299
57
  return;
300
58
  }
301
59
  const antdMajorVersion = getAntdMajorVersion(api.context.rootPath);
302
60
  if (antdMajorVersion && antdMajorVersion < 5) {
303
- (_c = rsbuildConfig.source) != null ? _c : rsbuildConfig.source = {};
61
+ rsbuildConfig.source ?? (rsbuildConfig.source = {});
304
62
  rsbuildConfig.source.transformImport = [
305
63
  ...rsbuildConfig.source.transformImport || [],
306
64
  {
@@ -324,7 +82,7 @@ var applyArcoSupport = (api) => {
324
82
  return;
325
83
  }
326
84
  const isUseSSR = (0, import_shared2.isServerTarget)(api.context.target);
327
- if (!(transformImport == null ? void 0 : transformImport.some((item) => item.libraryName === ARCO_NAME))) {
85
+ if (!transformImport?.some((item) => item.libraryName === ARCO_NAME)) {
328
86
  transformImport.push({
329
87
  libraryName: ARCO_NAME,
330
88
  libraryDirectory: isUseSSR ? "lib" : "es",
@@ -332,7 +90,7 @@ var applyArcoSupport = (api) => {
332
90
  style: true
333
91
  });
334
92
  }
335
- if (!(transformImport == null ? void 0 : transformImport.some((item) => item.libraryName === ARCO_ICON))) {
93
+ if (!transformImport?.some((item) => item.libraryName === ARCO_ICON)) {
336
94
  transformImport.push({
337
95
  libraryName: ARCO_ICON,
338
96
  libraryDirectory: isUseSSR ? "react-icon-cjs" : "react-icon",
@@ -345,70 +103,55 @@ var applyArcoSupport = (api) => {
345
103
  };
346
104
 
347
105
  // src/splitChunks.ts
348
- var import_splitChunks = __toESM(require_splitChunks());
349
106
  var import_shared3 = require("@rsbuild/shared");
350
- async function splitByExperience(rootPath) {
351
- const experienceCacheGroup = {};
352
- const packageRegExps = {
353
- react: (0, import_splitChunks.createDependenciesRegExp)(
354
- "react",
355
- "react-dom",
356
- "scheduler",
357
- ...(0, import_shared3.isProd)() ? [] : ["react-refresh", "@pmmmwh/react-refresh-webpack-plugin"]
358
- ),
359
- router: (0, import_splitChunks.createDependenciesRegExp)(
360
- "react-router",
361
- "react-router-dom",
362
- "@remix-run/router",
363
- "history"
364
- )
365
- };
366
- if ((0, import_shared3.isPackageInstalled)("antd", rootPath)) {
367
- packageRegExps.antd = (0, import_splitChunks.createDependenciesRegExp)("antd");
368
- }
369
- if ((0, import_shared3.isPackageInstalled)("@arco-design/web-react", rootPath)) {
370
- packageRegExps.arco = (0, import_splitChunks.createDependenciesRegExp)(/@?arco-design/);
371
- }
372
- if ((0, import_shared3.isPackageInstalled)("@douyinfe/semi-ui", rootPath)) {
373
- packageRegExps.semi = (0, import_splitChunks.createDependenciesRegExp)(
374
- /@(ies|douyinfe)[\\/]semi-.*/
375
- );
376
- }
377
- Object.entries(packageRegExps).forEach(([name, test]) => {
378
- const key = `lib-${name}`;
379
- experienceCacheGroup[key] = {
380
- test,
381
- priority: 0,
382
- name: key,
383
- reuseExistingChunk: true
384
- };
385
- });
386
- return experienceCacheGroup;
387
- }
388
- var applySplitChunksRule = (api) => {
389
- api.modifyRsbuildConfig(async (rsbuildConfig) => {
390
- const { chunkSplit } = rsbuildConfig.performance || {};
391
- if ((chunkSplit == null ? void 0 : chunkSplit.strategy) !== "split-by-experience") {
107
+ var applySplitChunksRule = (api, options = {
108
+ react: true,
109
+ router: true
110
+ }) => {
111
+ api.modifyBundlerChain((chain) => {
112
+ const config = api.getNormalizedConfig();
113
+ if (config.performance.chunkSplit.strategy !== "split-by-experience") {
392
114
  return;
393
115
  }
394
- const cacheGroups = await splitByExperience(api.context.rootPath);
395
- const override = rsbuildConfig.performance.chunkSplit.override;
396
- rsbuildConfig.performance.chunkSplit.override = {
116
+ const currentConfig = chain.optimization.splitChunks.values();
117
+ if (!(0, import_shared3.isPlainObject)(currentConfig)) {
118
+ return;
119
+ }
120
+ const extraGroups = {};
121
+ if (options.react) {
122
+ extraGroups.react = [
123
+ "react",
124
+ "react-dom",
125
+ "scheduler",
126
+ ...(0, import_shared3.isProd)() ? [] : ["react-refresh", "@rspack/plugin-react-refresh"]
127
+ ];
128
+ }
129
+ if (options.router) {
130
+ extraGroups.router = [
131
+ "react-router",
132
+ "react-router-dom",
133
+ "@remix-run/router",
134
+ "history"
135
+ ];
136
+ }
137
+ if (!Object.keys(extraGroups).length) {
138
+ return;
139
+ }
140
+ chain.optimization.splitChunks({
141
+ ...currentConfig,
397
142
  cacheGroups: {
398
- ...cacheGroups,
399
- ...override ? override.cacheGroups : {}
400
- },
401
- ...override || {}
402
- };
143
+ ...currentConfig.cacheGroups,
144
+ ...(0, import_shared3.createCacheGroups)(extraGroups)
145
+ }
146
+ });
403
147
  });
404
148
  };
405
149
 
406
150
  // src/react.ts
407
151
  var import_shared4 = require("@rsbuild/shared");
408
152
  function getReactRefreshEntry(compiler) {
409
- var _a, _b, _c, _d, _e;
410
- const hot = (_b = (_a = compiler.options.devServer) == null ? void 0 : _a.hot) != null ? _b : true;
411
- const refresh = (_e = (_d = (_c = compiler.options.builtins) == null ? void 0 : _c.react) == null ? void 0 : _d.refresh) != null ? _e : true;
153
+ const hot = compiler.options.devServer?.hot ?? true;
154
+ const refresh = compiler.options.builtins?.react?.refresh ?? true;
412
155
  if (hot && refresh) {
413
156
  const reactRefreshEntryPath = require.resolve("@rspack/plugin-react-refresh/react-refresh-entry");
414
157
  return reactRefreshEntryPath;
@@ -467,28 +210,46 @@ var applyBasicReactSupport = (api) => {
467
210
  if (!usingHMR) {
468
211
  return;
469
212
  }
470
- const { default: ReactRefreshRspackPlugin } = await import(
471
- // TODO https://github.com/web-infra-dev/rspack/issues/4471
472
- "@rspack/plugin-react-refresh"
473
- );
213
+ const { default: ReactRefreshRspackPlugin } = await import("@rspack/plugin-react-refresh");
474
214
  chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).use(ReactRefreshRspackPlugin);
475
215
  });
476
216
  };
477
217
 
218
+ // src/utils.ts
219
+ var import_fs = __toESM(require("fs"));
220
+ var import_semver = __toESM(require("semver"));
221
+ var import_shared5 = require("@rsbuild/shared");
222
+ var isBeyondReact17 = async (cwd) => {
223
+ const pkgPath = await (0, import_shared5.findUp)({ cwd, filename: "package.json" });
224
+ if (!pkgPath) {
225
+ return false;
226
+ }
227
+ const pkgInfo = JSON.parse(import_fs.default.readFileSync(pkgPath, "utf8"));
228
+ const deps = {
229
+ ...pkgInfo.devDependencies,
230
+ ...pkgInfo.dependencies
231
+ };
232
+ if (typeof deps.react !== "string") {
233
+ return false;
234
+ }
235
+ return import_semver.default.satisfies(import_semver.default.minVersion(deps.react), ">=17.0.0");
236
+ };
237
+
478
238
  // src/index.ts
479
- var pluginReact = () => ({
480
- name: "plugin-react",
481
- pre: ["plugin-swc"],
239
+ var pluginReact = (options = {}) => ({
240
+ name: "rsbuild:react",
241
+ pre: ["rsbuild:swc"],
482
242
  setup(api) {
483
243
  if (api.context.bundlerType === "rspack") {
484
244
  applyBasicReactSupport(api);
485
245
  }
486
246
  applyAntdSupport(api);
487
247
  applyArcoSupport(api);
488
- applySplitChunksRule(api);
248
+ applySplitChunksRule(api, options?.splitChunks);
489
249
  }
490
250
  });
491
251
  // Annotate the CommonJS export names for ESM import in node:
492
252
  0 && (module.exports = {
253
+ isBeyondReact17,
493
254
  pluginReact
494
255
  });
package/dist/index.mjs CHANGED
@@ -1,9 +1,3 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
1
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
2
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
3
  }) : x)(function(x) {
@@ -11,295 +5,16 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
11
5
  return require.apply(this, arguments);
12
6
  throw Error('Dynamic require of "' + x + '" is not supported');
13
7
  });
14
- var __esm = (fn, res) => function __init() {
15
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
16
- };
17
- var __commonJS = (cb, mod) => function __require2() {
18
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
19
- };
20
- var __copyProps = (to, from, except, desc) => {
21
- if (from && typeof from === "object" || typeof from === "function") {
22
- for (let key of __getOwnPropNames(from))
23
- if (!__hasOwnProp.call(to, key) && key !== except)
24
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
- }
26
- return to;
27
- };
28
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
- // If the importer is in node compatibility mode or this is not an ESM
30
- // file that has been converted to a CommonJS file using a Babel-
31
- // compatible transform (i.e. "__esModule" has not been set), then set
32
- // "default" to the CommonJS "module.exports" for node compatibility.
33
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
- mod
35
- ));
36
8
 
37
- // ../../node_modules/.pnpm/@modern-js+module-tools@2.40.0_typescript@5.2.2/node_modules/@modern-js/module-tools/shims/esm.js
9
+ // ../../node_modules/.pnpm/@modern-js+module-tools@2.41.0_typescript@5.3.2/node_modules/@modern-js/module-tools/shims/esm.js
38
10
  import { fileURLToPath } from "url";
39
11
  import path from "path";
40
- var init_esm = __esm({
41
- "../../node_modules/.pnpm/@modern-js+module-tools@2.40.0_typescript@5.2.2/node_modules/@modern-js/module-tools/shims/esm.js"() {
42
- "use strict";
43
- }
44
- });
45
12
 
46
- // ../../scripts/require_shims.js
13
+ // ../../scripts/requireShims.js
47
14
  import { createRequire } from "module";
48
- var init_require_shims = __esm({
49
- "../../scripts/require_shims.js"() {
50
- "use strict";
51
- global.require = createRequire(import.meta.url);
52
- }
53
- });
54
-
55
- // ../core/dist/plugins/splitChunks.js
56
- var require_splitChunks = __commonJS({
57
- "../core/dist/plugins/splitChunks.js"(exports, module) {
58
- "use strict";
59
- init_esm();
60
- init_require_shims();
61
- var __create2 = Object.create;
62
- var __defProp2 = Object.defineProperty;
63
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
64
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
65
- var __getProtoOf2 = Object.getPrototypeOf;
66
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
67
- var __export = (target, all) => {
68
- for (var name in all)
69
- __defProp2(target, name, { get: all[name], enumerable: true });
70
- };
71
- var __copyProps2 = (to, from, except, desc) => {
72
- if (from && typeof from === "object" || typeof from === "function") {
73
- for (let key of __getOwnPropNames2(from))
74
- if (!__hasOwnProp2.call(to, key) && key !== except)
75
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
76
- }
77
- return to;
78
- };
79
- var __toESM2 = (mod, isNodeMode, target) => (target = mod != null ? __create2(__getProtoOf2(mod)) : {}, __copyProps2(
80
- // If the importer is in node compatibility mode or this is not an ESM
81
- // file that has been converted to a CommonJS file using a Babel-
82
- // compatible transform (i.e. "__esModule" has not been set), then set
83
- // "default" to the CommonJS "module.exports" for node compatibility.
84
- isNodeMode || !mod || !mod.__esModule ? __defProp2(target, "default", { value: mod, enumerable: true }) : target,
85
- mod
86
- ));
87
- var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
88
- var splitChunks_exports = {};
89
- __export(splitChunks_exports, {
90
- createDependenciesRegExp: () => createDependenciesRegExp2,
91
- pluginSplitChunks: () => pluginSplitChunks
92
- });
93
- module.exports = __toCommonJS(splitChunks_exports);
94
- var import_assert = __toESM2(__require("assert"));
95
- var import_shared5 = __require("@rsbuild/shared");
96
- function getUserDefinedCacheGroups(forceSplitting) {
97
- const cacheGroups = {};
98
- const pairs = Array.isArray(forceSplitting) ? forceSplitting.map(
99
- (regexp, index) => [`force-split-${index}`, regexp]
100
- ) : Object.entries(forceSplitting);
101
- pairs.forEach(([key, regexp]) => {
102
- cacheGroups[key] = {
103
- test: regexp,
104
- name: key,
105
- chunks: "all",
106
- // Ignore minimum size, minimum chunks and maximum requests and always create chunks for user defined cache group.
107
- enforce: true
108
- };
109
- });
110
- return cacheGroups;
111
- }
112
- var DEPENDENCY_MATCH_TEMPL = /[\\/]node_modules[\\/](<SOURCES>)[\\/]/.source;
113
- var createDependenciesRegExp2 = (...dependencies) => {
114
- const sources = dependencies.map(
115
- (d) => typeof d === "string" ? d : d.source
116
- );
117
- const expr = DEPENDENCY_MATCH_TEMPL.replace("<SOURCES>", sources.join("|"));
118
- return new RegExp(expr);
119
- };
120
- function splitByExperience2(ctx) {
121
- const { override, polyfill, defaultConfig, userDefinedCacheGroups } = ctx;
122
- const experienceCacheGroup = {};
123
- const packageRegExps = {
124
- lodash: createDependenciesRegExp2("lodash", "lodash-es"),
125
- axios: createDependenciesRegExp2("axios", /axios-.+/)
126
- };
127
- if (polyfill === "entry" || polyfill === "usage") {
128
- packageRegExps.polyfill = createDependenciesRegExp2(
129
- "tslib",
130
- "core-js",
131
- "@babel/runtime",
132
- "@swc/helpers"
133
- );
134
- }
135
- Object.entries(packageRegExps).forEach(([name, test]) => {
136
- const key = `lib-${name}`;
137
- experienceCacheGroup[key] = {
138
- test,
139
- priority: 0,
140
- name: key,
141
- reuseExistingChunk: true
142
- };
143
- });
144
- return {
145
- ...defaultConfig,
146
- ...override,
147
- cacheGroups: {
148
- ...defaultConfig.cacheGroups,
149
- ...experienceCacheGroup,
150
- ...userDefinedCacheGroups,
151
- ...override.cacheGroups
152
- }
153
- };
154
- }
155
- function splitByModule(ctx) {
156
- const { override, userDefinedCacheGroups, defaultConfig } = ctx;
157
- return {
158
- ...defaultConfig,
159
- minSize: 0,
160
- maxInitialRequests: Infinity,
161
- ...override,
162
- cacheGroups: {
163
- ...defaultConfig.cacheGroups,
164
- ...userDefinedCacheGroups,
165
- // Core group
166
- vendors: {
167
- priority: -10,
168
- test: import_shared5.NODE_MODULES_REGEX,
169
- // todo: not support in rspack
170
- // @ts-expect-error
171
- name(module2) {
172
- return (0, import_shared5.getPackageNameFromModulePath)(module2.context);
173
- }
174
- },
175
- ...override.cacheGroups
176
- }
177
- };
178
- }
179
- function splitBySize(ctx) {
180
- var _a, _b;
181
- const { override, userDefinedCacheGroups, defaultConfig, rsbuildConfig } = ctx;
182
- (0, import_assert.default)(rsbuildConfig.strategy === "split-by-size");
183
- return {
184
- ...defaultConfig,
185
- minSize: (_a = rsbuildConfig.minSize) != null ? _a : 0,
186
- maxSize: (_b = rsbuildConfig.maxSize) != null ? _b : Infinity,
187
- ...override,
188
- cacheGroups: {
189
- ...defaultConfig.cacheGroups,
190
- ...userDefinedCacheGroups,
191
- ...override.cacheGroups
192
- }
193
- };
194
- }
195
- function splitCustom(ctx) {
196
- const { override, userDefinedCacheGroups, defaultConfig } = ctx;
197
- return {
198
- ...defaultConfig,
199
- ...override,
200
- cacheGroups: {
201
- ...defaultConfig.cacheGroups,
202
- ...userDefinedCacheGroups,
203
- ...override.cacheGroups
204
- }
205
- };
206
- }
207
- function allInOne(_ctx) {
208
- return false;
209
- }
210
- function singleVendor(ctx) {
211
- const { override, defaultConfig, userDefinedCacheGroups } = ctx;
212
- const singleVendorCacheGroup = {
213
- singleVendor: {
214
- test: import_shared5.NODE_MODULES_REGEX,
215
- priority: 0,
216
- chunks: "all",
217
- name: "vendor",
218
- enforce: true,
219
- reuseExistingChunk: true
220
- }
221
- };
222
- return {
223
- ...defaultConfig,
224
- ...override,
225
- cacheGroups: {
226
- ...defaultConfig.cacheGroups,
227
- ...singleVendorCacheGroup,
228
- ...userDefinedCacheGroups,
229
- ...override.cacheGroups
230
- }
231
- };
232
- }
233
- var SPLIT_STRATEGY_DISPATCHER = {
234
- "split-by-experience": splitByExperience2,
235
- "split-by-module": splitByModule,
236
- "split-by-size": splitBySize,
237
- custom: splitCustom,
238
- "all-in-one": allInOne,
239
- "single-vendor": singleVendor
240
- };
241
- function pluginSplitChunks() {
242
- return {
243
- name: "plugin-split-chunks",
244
- setup(api) {
245
- api.modifyBundlerChain(
246
- async (chain, { isServer, isWebWorker, isServiceWorker }) => {
247
- var _a;
248
- if (isServer || isWebWorker || isServiceWorker) {
249
- chain.optimization.splitChunks(false);
250
- if (isWebWorker || isServiceWorker) {
251
- chain.module.parser.merge({
252
- javascript: {
253
- dynamicImportMode: "eager"
254
- }
255
- });
256
- }
257
- return;
258
- }
259
- const config = api.getNormalizedConfig();
260
- const defaultConfig = {
261
- // Optimize both `initial` and `async` chunks
262
- chunks: "all",
263
- // When chunk size >= 50000 bytes, split it into separate chunk
264
- // @ts-expect-error Rspack type missing
265
- enforceSizeThreshold: 5e4,
266
- cacheGroups: {}
267
- };
268
- const { chunkSplit } = config.performance;
269
- let userDefinedCacheGroups = {};
270
- if (chunkSplit.forceSplitting) {
271
- userDefinedCacheGroups = getUserDefinedCacheGroups(
272
- chunkSplit.forceSplitting
273
- );
274
- }
275
- const override = chunkSplit.strategy === "custom" ? (
276
- // `chunkSplit.splitChunks` compat for Eden
277
- (_a = chunkSplit.splitChunks) != null ? _a : chunkSplit.override
278
- ) : chunkSplit.override;
279
- const splitChunksOptions = await SPLIT_STRATEGY_DISPATCHER[chunkSplit.strategy]({
280
- defaultConfig,
281
- override: override || {},
282
- userDefinedCacheGroups,
283
- rsbuildConfig: chunkSplit,
284
- rootPath: api.context.rootPath,
285
- polyfill: config.output.polyfill
286
- });
287
- chain.optimization.splitChunks(splitChunksOptions);
288
- }
289
- );
290
- }
291
- };
292
- }
293
- }
294
- });
295
-
296
- // src/index.ts
297
- init_esm();
298
- init_require_shims();
15
+ global.require = createRequire(import.meta.url);
299
16
 
300
17
  // src/antd.ts
301
- init_esm();
302
- init_require_shims();
303
18
  import { isServerTarget } from "@rsbuild/shared";
304
19
  var getAntdMajorVersion = (appDirectory) => {
305
20
  try {
@@ -336,8 +51,6 @@ var applyAntdSupport = (api) => {
336
51
  };
337
52
 
338
53
  // src/arco.ts
339
- init_esm();
340
- init_require_shims();
341
54
  import {
342
55
  isServerTarget as isServerTarget2,
343
56
  isPackageInstalled
@@ -372,72 +85,55 @@ var applyArcoSupport = (api) => {
372
85
  };
373
86
 
374
87
  // src/splitChunks.ts
375
- init_esm();
376
- init_require_shims();
377
- var import_splitChunks = __toESM(require_splitChunks());
378
88
  import {
379
89
  isProd,
380
- isPackageInstalled as isPackageInstalled2
90
+ isPlainObject,
91
+ createCacheGroups
381
92
  } from "@rsbuild/shared";
382
- async function splitByExperience(rootPath) {
383
- const experienceCacheGroup = {};
384
- const packageRegExps = {
385
- react: (0, import_splitChunks.createDependenciesRegExp)(
386
- "react",
387
- "react-dom",
388
- "scheduler",
389
- ...isProd() ? [] : ["react-refresh", "@pmmmwh/react-refresh-webpack-plugin"]
390
- ),
391
- router: (0, import_splitChunks.createDependenciesRegExp)(
392
- "react-router",
393
- "react-router-dom",
394
- "@remix-run/router",
395
- "history"
396
- )
397
- };
398
- if (isPackageInstalled2("antd", rootPath)) {
399
- packageRegExps.antd = (0, import_splitChunks.createDependenciesRegExp)("antd");
400
- }
401
- if (isPackageInstalled2("@arco-design/web-react", rootPath)) {
402
- packageRegExps.arco = (0, import_splitChunks.createDependenciesRegExp)(/@?arco-design/);
403
- }
404
- if (isPackageInstalled2("@douyinfe/semi-ui", rootPath)) {
405
- packageRegExps.semi = (0, import_splitChunks.createDependenciesRegExp)(
406
- /@(ies|douyinfe)[\\/]semi-.*/
407
- );
408
- }
409
- Object.entries(packageRegExps).forEach(([name, test]) => {
410
- const key = `lib-${name}`;
411
- experienceCacheGroup[key] = {
412
- test,
413
- priority: 0,
414
- name: key,
415
- reuseExistingChunk: true
416
- };
417
- });
418
- return experienceCacheGroup;
419
- }
420
- var applySplitChunksRule = (api) => {
421
- api.modifyRsbuildConfig(async (rsbuildConfig) => {
422
- const { chunkSplit } = rsbuildConfig.performance || {};
423
- if (chunkSplit?.strategy !== "split-by-experience") {
93
+ var applySplitChunksRule = (api, options = {
94
+ react: true,
95
+ router: true
96
+ }) => {
97
+ api.modifyBundlerChain((chain) => {
98
+ const config = api.getNormalizedConfig();
99
+ if (config.performance.chunkSplit.strategy !== "split-by-experience") {
100
+ return;
101
+ }
102
+ const currentConfig = chain.optimization.splitChunks.values();
103
+ if (!isPlainObject(currentConfig)) {
104
+ return;
105
+ }
106
+ const extraGroups = {};
107
+ if (options.react) {
108
+ extraGroups.react = [
109
+ "react",
110
+ "react-dom",
111
+ "scheduler",
112
+ ...isProd() ? [] : ["react-refresh", "@rspack/plugin-react-refresh"]
113
+ ];
114
+ }
115
+ if (options.router) {
116
+ extraGroups.router = [
117
+ "react-router",
118
+ "react-router-dom",
119
+ "@remix-run/router",
120
+ "history"
121
+ ];
122
+ }
123
+ if (!Object.keys(extraGroups).length) {
424
124
  return;
425
125
  }
426
- const cacheGroups = await splitByExperience(api.context.rootPath);
427
- const override = rsbuildConfig.performance.chunkSplit.override;
428
- rsbuildConfig.performance.chunkSplit.override = {
126
+ chain.optimization.splitChunks({
127
+ ...currentConfig,
429
128
  cacheGroups: {
430
- ...cacheGroups,
431
- ...override ? override.cacheGroups : {}
432
- },
433
- ...override || {}
434
- };
129
+ ...currentConfig.cacheGroups,
130
+ ...createCacheGroups(extraGroups)
131
+ }
132
+ });
435
133
  });
436
134
  };
437
135
 
438
136
  // src/react.ts
439
- init_esm();
440
- init_require_shims();
441
137
  import { isUsingHMR, isClientCompiler, isProd as isProd2 } from "@rsbuild/shared";
442
138
  function getReactRefreshEntry(compiler) {
443
139
  const hot = compiler.options.devServer?.hot ?? true;
@@ -502,27 +198,45 @@ var applyBasicReactSupport = (api) => {
502
198
  if (!usingHMR) {
503
199
  return;
504
200
  }
505
- const { default: ReactRefreshRspackPlugin } = await import(
506
- // TODO https://github.com/web-infra-dev/rspack/issues/4471
507
- "@rspack/plugin-react-refresh"
508
- );
201
+ const { default: ReactRefreshRspackPlugin } = await import("@rspack/plugin-react-refresh");
509
202
  chain.plugin(CHAIN_ID.PLUGIN.REACT_FAST_REFRESH).use(ReactRefreshRspackPlugin);
510
203
  });
511
204
  };
512
205
 
206
+ // src/utils.ts
207
+ import fs from "fs";
208
+ import semver from "semver";
209
+ import { findUp } from "@rsbuild/shared";
210
+ var isBeyondReact17 = async (cwd) => {
211
+ const pkgPath = await findUp({ cwd, filename: "package.json" });
212
+ if (!pkgPath) {
213
+ return false;
214
+ }
215
+ const pkgInfo = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
216
+ const deps = {
217
+ ...pkgInfo.devDependencies,
218
+ ...pkgInfo.dependencies
219
+ };
220
+ if (typeof deps.react !== "string") {
221
+ return false;
222
+ }
223
+ return semver.satisfies(semver.minVersion(deps.react), ">=17.0.0");
224
+ };
225
+
513
226
  // src/index.ts
514
- var pluginReact = () => ({
515
- name: "plugin-react",
516
- pre: ["plugin-swc"],
227
+ var pluginReact = (options = {}) => ({
228
+ name: "rsbuild:react",
229
+ pre: ["rsbuild:swc"],
517
230
  setup(api) {
518
231
  if (api.context.bundlerType === "rspack") {
519
232
  applyBasicReactSupport(api);
520
233
  }
521
234
  applyAntdSupport(api);
522
235
  applyArcoSupport(api);
523
- applySplitChunksRule(api);
236
+ applySplitChunksRule(api, options?.splitChunks);
524
237
  }
525
238
  });
526
239
  export {
240
+ isBeyondReact17,
527
241
  pluginReact
528
242
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/plugin-react",
3
- "version": "0.0.0-next-20231115072032",
3
+ "version": "0.0.0-next-20231207110454",
4
4
  "description": "React plugin for Rsbuild",
5
5
  "repository": {
6
6
  "type": "git",
@@ -8,6 +8,7 @@
8
8
  "directory": "packages/plugin-react"
9
9
  },
10
10
  "license": "MIT",
11
+ "type": "commonjs",
11
12
  "exports": {
12
13
  ".": {
13
14
  "types": "./dist/index.d.ts",
@@ -21,15 +22,17 @@
21
22
  "dist"
22
23
  ],
23
24
  "dependencies": {
24
- "@rspack/plugin-react-refresh": "0.3.12",
25
+ "@rspack/plugin-react-refresh": "0.4.2",
25
26
  "react-refresh": "^0.14.0",
26
- "@rsbuild/shared": "0.0.0-next-20231115072032"
27
+ "semver": "^7.5.4",
28
+ "@rsbuild/shared": "0.0.0-next-20231207110454"
27
29
  },
28
30
  "devDependencies": {
29
31
  "@types/node": "^16",
30
- "typescript": "^5.2.2",
31
- "@rsbuild/test-helper": "0.0.0-next-20231115072032",
32
- "@rsbuild/core": "0.0.0-next-20231115072032"
32
+ "@types/semver": "^7.5.4",
33
+ "typescript": "^5.3.0",
34
+ "@rsbuild/core": "0.0.0-next-20231207110454",
35
+ "@rsbuild/test-helper": "0.0.0-next-20231207110454"
33
36
  },
34
37
  "publishConfig": {
35
38
  "access": "public",