@rsbuild/core 1.4.7 → 1.4.8

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.cjs CHANGED
@@ -1607,47 +1607,6 @@ ${section.body}` : section.body).join("\n\n"));
1607
1607
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1608
1608
  }
1609
1609
  }
1610
- let RSBUILD_ALL_ENVIRONMENT_SYMBOL = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL', isPluginMatchEnvironment = (pluginEnvironment, currentEnvironment)=>pluginEnvironment === currentEnvironment || pluginEnvironment === RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1611
- async function initPlugins({ getPluginAPI, pluginManager }) {
1612
- index_js_namespaceObject.logger.debug('init plugins');
1613
- let plugins = ((plugins)=>{
1614
- let allLines = [];
1615
- function getPlugin(name) {
1616
- let targets = plugins.filter((item)=>item.instance.name === name);
1617
- if (!targets.length) throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_index_js_default().yellow(name)}" not existed`);
1618
- return targets;
1619
- }
1620
- for (let plugin of plugins){
1621
- if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1622
- pre,
1623
- plugin.instance.name
1624
- ]);
1625
- if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1626
- plugin.instance.name,
1627
- post
1628
- ]);
1629
- }
1630
- let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1631
- for(; zeroEndPoints.length;){
1632
- let zep = zeroEndPoints.shift();
1633
- sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1634
- }
1635
- if (allLines.length) {
1636
- let restInRingPoints = {};
1637
- for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1638
- throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_index_js_default().yellow(Object.keys(restInRingPoints).join(','))}`);
1639
- }
1640
- return sortedPoint;
1641
- })(pluginManager.getAllPluginsWithMeta()), removedPlugins = plugins.reduce((ret, plugin)=>(plugin.instance.remove && (ret[plugin.environment] ??= [], ret[plugin.environment].push(...plugin.instance.remove)), ret), {});
1642
- for (let plugin of plugins){
1643
- var _removedPlugins_plugin_environment, _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1644
- let isGlobalPlugin = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL' === plugin.environment;
1645
- if ((null == (_removedPlugins_plugin_environment = removedPlugins[plugin.environment]) ? void 0 : _removedPlugins_plugin_environment.includes(plugin.instance.name)) || !isGlobalPlugin && (null == (_removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL = removedPlugins[RSBUILD_ALL_ENVIRONMENT_SYMBOL]) ? void 0 : _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL.includes(plugin.instance.name))) continue;
1646
- let { instance, environment } = plugin;
1647
- await instance.setup(getPluginAPI(environment));
1648
- }
1649
- index_js_namespaceObject.logger.debug('init plugins done');
1650
- }
1651
1610
  function createEnvironmentAsyncHook() {
1652
1611
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
1653
1612
  isFunction(cb) ? defaultGroup.push({
@@ -1675,7 +1634,7 @@ ${section.body}` : section.body).join("\n\n"));
1675
1634
  ...defaultGroup,
1676
1635
  ...postGroup
1677
1636
  ]){
1678
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1637
+ if (environment && callback.environment && callback.environment !== environment) continue;
1679
1638
  let result = await callback.handler(...params);
1680
1639
  void 0 !== result && (params[0] = result);
1681
1640
  }
@@ -1688,7 +1647,7 @@ ${section.body}` : section.body).join("\n\n"));
1688
1647
  ...defaultGroup,
1689
1648
  ...postGroup
1690
1649
  ]){
1691
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1650
+ if (environment && callback.environment && callback.environment !== environment) continue;
1692
1651
  let result = await callback.handler(...params);
1693
1652
  results.push(result);
1694
1653
  }
@@ -2131,6 +2090,57 @@ ${section.body}` : section.body).join("\n\n"));
2131
2090
  }
2132
2091
  }
2133
2092
  }
2093
+ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
2094
+ async function initPlugins({ context, pluginManager }) {
2095
+ index_js_namespaceObject.logger.debug('init plugins');
2096
+ let plugins = ((plugins)=>{
2097
+ let allLines = [];
2098
+ function getPlugin(name) {
2099
+ let targets = plugins.filter((item)=>item.instance.name === name);
2100
+ if (!targets.length) throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_index_js_default().yellow(name)}" not existed`);
2101
+ return targets;
2102
+ }
2103
+ for (let plugin of plugins){
2104
+ if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
2105
+ pre,
2106
+ plugin.instance.name
2107
+ ]);
2108
+ if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
2109
+ plugin.instance.name,
2110
+ post
2111
+ ]);
2112
+ }
2113
+ let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
2114
+ for(; zeroEndPoints.length;){
2115
+ let zep = zeroEndPoints.shift();
2116
+ sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
2117
+ }
2118
+ if (allLines.length) {
2119
+ let restInRingPoints = {};
2120
+ for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
2121
+ throw Error(`${picocolors_index_js_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_index_js_default().yellow(Object.keys(restInRingPoints).join(','))}`);
2122
+ }
2123
+ return sortedPoint;
2124
+ })(pluginManager.getAllPluginsWithMeta()), removedPlugins = new Set(), removedEnvPlugins = {};
2125
+ for (let { environment, instance } of plugins)if (instance.remove) if (environment) for (let item of (removedEnvPlugins[environment] ??= new Set(), instance.remove))removedEnvPlugins[environment].add(item);
2126
+ else for (let item of instance.remove)removedPlugins.add(item);
2127
+ for (let { instance, environment } of plugins){
2128
+ var _removedEnvPlugins_environment;
2129
+ let { name, setup } = instance;
2130
+ if (!(removedPlugins.has(name) || environment && (null == (_removedEnvPlugins_environment = removedEnvPlugins[environment]) ? void 0 : _removedEnvPlugins_environment.has(name)))) {
2131
+ if (instance.apply && context.action) {
2132
+ let expected = {
2133
+ build: 'build',
2134
+ dev: 'serve',
2135
+ preview: 'serve'
2136
+ }[context.action];
2137
+ if (expected && instance.apply !== expected) continue;
2138
+ }
2139
+ await setup(context.getPluginAPI(environment));
2140
+ }
2141
+ }
2142
+ index_js_namespaceObject.logger.debug('init plugins done');
2143
+ }
2134
2144
  let mapProcessAssetsStage = (compiler, stage)=>{
2135
2145
  let { Compilation } = compiler.webpack;
2136
2146
  switch(stage){
@@ -2250,7 +2260,7 @@ ${section.body}` : section.body).join("\n\n"));
2250
2260
  async function createContext(options, userConfig) {
2251
2261
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_namespaceObject.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2252
2262
  return {
2253
- version: "1.4.7",
2263
+ version: "1.4.8",
2254
2264
  rootPath,
2255
2265
  distPath: '',
2256
2266
  cachePath,
@@ -2640,7 +2650,7 @@ ${section.body}` : section.body).join("\n\n"));
2640
2650
  async function initRsbuildConfig({ context, pluginManager }) {
2641
2651
  if (context.normalizedConfig) return context.normalizedConfig;
2642
2652
  await initPlugins({
2643
- getPluginAPI: context.getPluginAPI,
2653
+ context,
2644
2654
  pluginManager
2645
2655
  }), await modifyRsbuildConfig(context);
2646
2656
  let normalizedBaseConfig = ((config)=>{
@@ -3809,13 +3819,13 @@ ${section.body}` : section.body).join("\n\n"));
3809
3819
  if (routes.length <= 1) {
3810
3820
  let pathname = routes.length ? routes[0].pathname : '';
3811
3821
  return urls.map(({ label, url })=>{
3812
- let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors_index_js_default().dim(label.padEnd(10))}`;
3822
+ let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors_index_js_default().dim(label.padEnd(10))}`;
3813
3823
  return ` ${prefix}${picocolors_index_js_default().cyan(normalizedPathname)}\n`;
3814
3824
  }).join('');
3815
3825
  }
3816
3826
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
3817
3827
  return urls.forEach(({ label, url }, index)=>{
3818
- for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors_index_js_default().dim('-')} ${picocolors_index_js_default().dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors_index_js_default().cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3828
+ for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors_index_js_default().dim('-')} ${picocolors_index_js_default().dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors_index_js_default().cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3819
3829
  }), message;
3820
3830
  }(urls, routes);
3821
3831
  return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), index_js_namespaceObject.logger.log(message), message;
@@ -4334,7 +4344,7 @@ ${section.body}` : section.body).join("\n\n"));
4334
4344
  }
4335
4345
  ].filter(Boolean);
4336
4346
  if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors_index_js_default().dim('[rsbuild:config]')} ${picocolors_index_js_default().yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
4337
- help && index_js_namespaceObject.logger.log(!0 === help ? ` \u{279C} ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4347
+ help && index_js_namespaceObject.logger.log(!0 === help ? ` \u{279C} ${picocolors_index_js_default().dim('press')} ${picocolors_index_js_default().bold('h + enter')} ${picocolors_index_js_default().dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4338
4348
  let { createInterface } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "node:readline")), rl = createInterface({
4339
4349
  input: process.stdin
4340
4350
  });
@@ -5492,15 +5502,22 @@ ${section.body}` : section.body).join("\n\n"));
5492
5502
  port: port1,
5493
5503
  https
5494
5504
  };
5495
- let waitFirstCompileDone = runCompile ? new Promise((resolve)=>{
5496
- context.hooks.onDevCompileDone.tap(({ stats, isFirstCompile })=>{
5497
- lastStats = 'stats' in stats ? stats.stats : [
5498
- stats
5499
- ], isFirstCompile && resolve();
5500
- });
5501
- }) : Promise.resolve(), startCompile = async ()=>{
5505
+ let waitLastCompileDoneResolve = null, waitLastCompileDone = new Promise((resolve)=>{
5506
+ waitLastCompileDoneResolve = resolve;
5507
+ });
5508
+ context.hooks.onDevCompileDone.tap(({ stats })=>{
5509
+ lastStats = 'stats' in stats ? stats.stats : [
5510
+ stats
5511
+ ], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
5512
+ });
5513
+ let startCompile = async ()=>{
5502
5514
  let compiler = customCompiler || await createCompiler();
5503
5515
  if (!compiler) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Failed to get compiler instance.`);
5516
+ null == compiler || compiler.hooks.watchRun.tap('rsbuild:watchRun', ()=>{
5517
+ lastStats && (waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null), waitLastCompileDone = new Promise((resolve)=>{
5518
+ waitLastCompileDoneResolve = resolve;
5519
+ }));
5520
+ });
5504
5521
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
5505
5522
  getPublicPathFromCompiler(compiler)
5506
5523
  ], compilationManager = new CompilationManager({
@@ -5558,19 +5575,19 @@ ${section.body}` : section.body).join("\n\n"));
5558
5575
  {
5559
5576
  getStats: async ()=>{
5560
5577
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getStats')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5561
- return await waitFirstCompileDone, lastStats[environment.index];
5578
+ return await waitLastCompileDone, lastStats[environment.index];
5562
5579
  },
5563
5580
  context: environment,
5564
5581
  loadBundle: async (entryName)=>{
5565
5582
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('loadBundle')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5566
- return await waitFirstCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5583
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5567
5584
  readFileSync: compilationManager.readFileSync,
5568
5585
  environment
5569
5586
  });
5570
5587
  },
5571
5588
  getTransformedHtml: async (entryName)=>{
5572
5589
  if (!compilationManager) throw Error(`${picocolors_index_js_default().dim('[rsbuild:server]')} Can not call ${picocolors_index_js_default().yellow('getTransformedHtml')} when ${picocolors_index_js_default().yellow('runCompile')} is false`);
5573
- return await waitFirstCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5590
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5574
5591
  readFileSync: compilationManager.readFileSync,
5575
5592
  environment
5576
5593
  });
@@ -7239,10 +7256,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7239
7256
  },
7240
7257
  {
7241
7258
  name: 'rsbuild:lazy-compilation',
7259
+ apply: 'serve',
7242
7260
  setup (api) {
7243
- api.modifyBundlerChain((chain, { environment, isProd, target })=>{
7261
+ api.modifyBundlerChain((chain, { environment, target })=>{
7244
7262
  var _config_dev;
7245
- if (isProd || 'web' !== target) return;
7263
+ if ('web' !== target) return;
7246
7264
  let { config } = environment, options = null == (_config_dev = config.dev) ? void 0 : _config_dev.lazyCompilation;
7247
7265
  if (options) {
7248
7266
  if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.experiments({
@@ -7359,12 +7377,10 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7359
7377
  ...options,
7360
7378
  rsbuildConfig: config
7361
7379
  }, pluginManager = (plugins = [], {
7362
- getPlugins: (options = {
7363
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7364
- })=>plugins.filter((p)=>isPluginMatchEnvironment(p.environment, options.environment)).map((p)=>p.instance),
7380
+ getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
7365
7381
  getAllPluginsWithMeta: ()=>plugins,
7366
7382
  addPlugins: (newPlugins, options)=>{
7367
- let { before, environment = RSBUILD_ALL_ENVIRONMENT_SYMBOL } = options || {};
7383
+ let { before, environment } = options || {};
7368
7384
  for (let newPlugin of newPlugins)if (newPlugin) {
7369
7385
  var plugin = newPlugin;
7370
7386
  let type = typeof plugin;
@@ -7406,9 +7422,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7406
7422
  removePlugins: (pluginNames, options = {})=>{
7407
7423
  plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
7408
7424
  },
7409
- isPluginExists: (pluginName, options = {
7410
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7411
- })=>!!plugins.find((plugin)=>plugin.instance.name === pluginName && isPluginMatchEnvironment(plugin.environment, options.environment))
7425
+ isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
7412
7426
  }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
7413
7427
  let { hooks } = context, publicContext = function(context) {
7414
7428
  let exposedKeys = [
@@ -7462,7 +7476,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7462
7476
  let pluginName = 'RsbuildCorePlugin';
7463
7477
  chain.plugin(pluginName).use(class {
7464
7478
  apply(compiler) {
7465
- for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7479
+ for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7466
7480
  normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
7467
7481
  compiler,
7468
7482
  compilation,
@@ -7475,7 +7489,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7475
7489
  childCompiler.__rsbuildTransformer = transformer;
7476
7490
  });
7477
7491
  let { sources } = compiler.webpack;
7478
- for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7492
+ for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7479
7493
  name: pluginName,
7480
7494
  stage: mapProcessAssetsStage(compiler, descriptor.stage)
7481
7495
  }, async (assets)=>handler({
@@ -7889,11 +7903,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7889
7903
  ].includes(level) && (index_js_namespaceObject.logger.level = level);
7890
7904
  }
7891
7905
  let { npm_execpath } = process.env;
7892
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.7\n`);
7906
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && index_js_namespaceObject.logger.log(), index_js_namespaceObject.logger.greet(` Rsbuild v1.4.8\n`);
7893
7907
  try {
7894
7908
  !function() {
7895
7909
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7896
- cli.help(), cli.version("1.4.7"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7910
+ cli.help(), cli.version("1.4.8"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7897
7911
  default: 'jiti'
7898
7912
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7899
7913
  type: [
@@ -7951,7 +7965,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7951
7965
  index_js_namespaceObject.logger.error('Failed to start Rsbuild CLI.'), index_js_namespaceObject.logger.error(err);
7952
7966
  }
7953
7967
  }
7954
- let src_version = "1.4.7";
7968
+ let src_version = "1.4.8";
7955
7969
  })(), exports.PLUGIN_CSS_NAME = __webpack_exports__.PLUGIN_CSS_NAME, exports.PLUGIN_SWC_NAME = __webpack_exports__.PLUGIN_SWC_NAME, exports.createRsbuild = __webpack_exports__.createRsbuild, exports.defaultAllowedOrigins = __webpack_exports__.defaultAllowedOrigins, exports.defineConfig = __webpack_exports__.defineConfig, exports.ensureAssetPrefix = __webpack_exports__.ensureAssetPrefix, exports.loadConfig = __webpack_exports__.loadConfig, exports.loadEnv = __webpack_exports__.loadEnv, exports.logger = __webpack_exports__.logger, exports.mergeRsbuildConfig = __webpack_exports__.mergeRsbuildConfig, exports.rspack = __webpack_exports__.rspack, exports.runCLI = __webpack_exports__.runCLI, exports.version = __webpack_exports__.version, __webpack_exports__)-1 === [
7956
7970
  "PLUGIN_CSS_NAME",
7957
7971
  "PLUGIN_SWC_NAME",
package/dist/index.js CHANGED
@@ -1428,47 +1428,6 @@ class CAC extends EventEmitter {
1428
1428
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1429
1429
  }
1430
1430
  }
1431
- let RSBUILD_ALL_ENVIRONMENT_SYMBOL = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL', isPluginMatchEnvironment = (pluginEnvironment, currentEnvironment)=>pluginEnvironment === currentEnvironment || pluginEnvironment === RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1432
- async function initPlugins({ getPluginAPI, pluginManager }) {
1433
- logger.debug('init plugins');
1434
- let plugins = ((plugins)=>{
1435
- let allLines = [];
1436
- function getPlugin(name) {
1437
- let targets = plugins.filter((item)=>item.instance.name === name);
1438
- if (!targets.length) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugin "${picocolors.yellow(name)}" not existed`);
1439
- return targets;
1440
- }
1441
- for (let plugin of plugins){
1442
- if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1443
- pre,
1444
- plugin.instance.name
1445
- ]);
1446
- if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1447
- plugin.instance.name,
1448
- post
1449
- ]);
1450
- }
1451
- let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1452
- for(; zeroEndPoints.length;){
1453
- let zep = zeroEndPoints.shift();
1454
- sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1455
- }
1456
- if (allLines.length) {
1457
- let restInRingPoints = {};
1458
- for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1459
- throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors.yellow(Object.keys(restInRingPoints).join(','))}`);
1460
- }
1461
- return sortedPoint;
1462
- })(pluginManager.getAllPluginsWithMeta()), removedPlugins = plugins.reduce((ret, plugin)=>(plugin.instance.remove && (ret[plugin.environment] ??= [], ret[plugin.environment].push(...plugin.instance.remove)), ret), {});
1463
- for (let plugin of plugins){
1464
- var _removedPlugins_plugin_environment, _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL;
1465
- let isGlobalPlugin = 'RSBUILD_ALL_ENVIRONMENT_SYMBOL' === plugin.environment;
1466
- if ((null == (_removedPlugins_plugin_environment = removedPlugins[plugin.environment]) ? void 0 : _removedPlugins_plugin_environment.includes(plugin.instance.name)) || !isGlobalPlugin && (null == (_removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL = removedPlugins[RSBUILD_ALL_ENVIRONMENT_SYMBOL]) ? void 0 : _removedPlugins_RSBUILD_ALL_ENVIRONMENT_SYMBOL.includes(plugin.instance.name))) continue;
1467
- let { instance, environment } = plugin;
1468
- await instance.setup(getPluginAPI(environment));
1469
- }
1470
- logger.debug('init plugins done');
1471
- }
1472
1431
  function createEnvironmentAsyncHook() {
1473
1432
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
1474
1433
  isFunction(cb) ? defaultGroup.push({
@@ -1496,7 +1455,7 @@ function createEnvironmentAsyncHook() {
1496
1455
  ...defaultGroup,
1497
1456
  ...postGroup
1498
1457
  ]){
1499
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1458
+ if (environment && callback.environment && callback.environment !== environment) continue;
1500
1459
  let result = await callback.handler(...params);
1501
1460
  void 0 !== result && (params[0] = result);
1502
1461
  }
@@ -1509,7 +1468,7 @@ function createEnvironmentAsyncHook() {
1509
1468
  ...defaultGroup,
1510
1469
  ...postGroup
1511
1470
  ]){
1512
- if (callback.environment && environment && !isPluginMatchEnvironment(callback.environment, environment)) continue;
1471
+ if (environment && callback.environment && callback.environment !== environment) continue;
1513
1472
  let result = await callback.handler(...params);
1514
1473
  results.push(result);
1515
1474
  }
@@ -1946,6 +1905,57 @@ function exit(exitCode, type) {
1946
1905
  }
1947
1906
  }
1948
1907
  }
1908
+ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
1909
+ async function initPlugins({ context, pluginManager }) {
1910
+ logger.debug('init plugins');
1911
+ let plugins = ((plugins)=>{
1912
+ let allLines = [];
1913
+ function getPlugin(name) {
1914
+ let targets = plugins.filter((item)=>item.instance.name === name);
1915
+ if (!targets.length) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugin "${picocolors.yellow(name)}" not existed`);
1916
+ return targets;
1917
+ }
1918
+ for (let plugin of plugins){
1919
+ if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && plugins.some((item)=>item.instance.name === pre) && allLines.push([
1920
+ pre,
1921
+ plugin.instance.name
1922
+ ]);
1923
+ if (plugin.instance.post) for (let post of plugin.instance.post)post && plugins.some((item)=>item.instance.name === post) && allLines.push([
1924
+ plugin.instance.name,
1925
+ post
1926
+ ]);
1927
+ }
1928
+ let zeroEndPoints = plugins.filter((item)=>!allLines.find((l)=>l[1] === item.instance.name)), sortedPoint = [];
1929
+ for(; zeroEndPoints.length;){
1930
+ let zep = zeroEndPoints.shift();
1931
+ sortedPoint.push(...getPlugin(zep.instance.name)), allLines = allLines.filter((l)=>l[0] !== getPlugin(zep.instance.name)[0].instance.name), zeroEndPoints = plugins.filter((item)=>!sortedPoint.find((sp)=>sp.instance.name === item.instance.name)).filter((item)=>!allLines.find((l)=>l[1] === item.instance.name));
1932
+ }
1933
+ if (allLines.length) {
1934
+ let restInRingPoints = {};
1935
+ for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
1936
+ throw Error(`${picocolors.dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors.yellow(Object.keys(restInRingPoints).join(','))}`);
1937
+ }
1938
+ return sortedPoint;
1939
+ })(pluginManager.getAllPluginsWithMeta()), removedPlugins = new Set(), removedEnvPlugins = {};
1940
+ for (let { environment, instance } of plugins)if (instance.remove) if (environment) for (let item of (removedEnvPlugins[environment] ??= new Set(), instance.remove))removedEnvPlugins[environment].add(item);
1941
+ else for (let item of instance.remove)removedPlugins.add(item);
1942
+ for (let { instance, environment } of plugins){
1943
+ var _removedEnvPlugins_environment;
1944
+ let { name, setup } = instance;
1945
+ if (!(removedPlugins.has(name) || environment && (null == (_removedEnvPlugins_environment = removedEnvPlugins[environment]) ? void 0 : _removedEnvPlugins_environment.has(name)))) {
1946
+ if (instance.apply && context.action) {
1947
+ let expected = {
1948
+ build: 'build',
1949
+ dev: 'serve',
1950
+ preview: 'serve'
1951
+ }[context.action];
1952
+ if (expected && instance.apply !== expected) continue;
1953
+ }
1954
+ await setup(context.getPluginAPI(environment));
1955
+ }
1956
+ }
1957
+ logger.debug('init plugins done');
1958
+ }
1949
1959
  let mapProcessAssetsStage = (compiler, stage)=>{
1950
1960
  let { Compilation } = compiler.webpack;
1951
1961
  switch(stage){
@@ -2065,7 +2075,7 @@ async function updateEnvironmentContext(context, configs) {
2065
2075
  async function createContext(options, userConfig) {
2066
2076
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2067
2077
  return {
2068
- version: "1.4.7",
2078
+ version: "1.4.8",
2069
2079
  rootPath,
2070
2080
  distPath: '',
2071
2081
  cachePath,
@@ -2448,7 +2458,7 @@ async function modifyEnvironmentConfig(context, config, name) {
2448
2458
  async function initRsbuildConfig({ context, pluginManager }) {
2449
2459
  if (context.normalizedConfig) return context.normalizedConfig;
2450
2460
  await initPlugins({
2451
- getPluginAPI: context.getPluginAPI,
2461
+ context,
2452
2462
  pluginManager
2453
2463
  }), await modifyRsbuildConfig(context);
2454
2464
  let normalizedBaseConfig = ((config)=>{
@@ -3614,13 +3624,13 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
3614
3624
  if (routes.length <= 1) {
3615
3625
  let pathname = routes.length ? routes[0].pathname : '';
3616
3626
  return urls.map(({ label, url })=>{
3617
- let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors.dim(label.padEnd(10))}`;
3627
+ let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `\u{279C} ${picocolors.dim(label.padEnd(10))}`;
3618
3628
  return ` ${prefix}${picocolors.cyan(normalizedPathname)}\n`;
3619
3629
  }).join('');
3620
3630
  }
3621
3631
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
3622
3632
  return urls.forEach(({ label, url }, index)=>{
3623
- for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3633
+ for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3624
3634
  }), message;
3625
3635
  }(urls, routes);
3626
3636
  return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
@@ -4135,7 +4145,7 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
4135
4145
  }
4136
4146
  ].filter(Boolean);
4137
4147
  if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors.dim('[rsbuild:config]')} ${picocolors.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
4138
- help && logger.log(!0 === help ? ` \u{279C} ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4148
+ help && logger.log(!0 === help ? ` \u{279C} ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` \u{279C} ${help}\n`);
4139
4149
  let { createInterface } = await import("node:readline"), rl = createInterface({
4140
4150
  input: process.stdin
4141
4151
  });
@@ -5282,15 +5292,22 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
5282
5292
  port,
5283
5293
  https
5284
5294
  };
5285
- let waitFirstCompileDone = runCompile ? new Promise((resolve)=>{
5286
- context.hooks.onDevCompileDone.tap(({ stats, isFirstCompile })=>{
5287
- lastStats = 'stats' in stats ? stats.stats : [
5288
- stats
5289
- ], isFirstCompile && resolve();
5290
- });
5291
- }) : Promise.resolve(), startCompile = async ()=>{
5295
+ let waitLastCompileDoneResolve = null, waitLastCompileDone = new Promise((resolve)=>{
5296
+ waitLastCompileDoneResolve = resolve;
5297
+ });
5298
+ context.hooks.onDevCompileDone.tap(({ stats })=>{
5299
+ lastStats = 'stats' in stats ? stats.stats : [
5300
+ stats
5301
+ ], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
5302
+ });
5303
+ let startCompile = async ()=>{
5292
5304
  let compiler = customCompiler || await createCompiler();
5293
5305
  if (!compiler) throw Error(`${picocolors.dim('[rsbuild:server]')} Failed to get compiler instance.`);
5306
+ null == compiler || compiler.hooks.watchRun.tap('rsbuild:watchRun', ()=>{
5307
+ lastStats && (waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null), waitLastCompileDone = new Promise((resolve)=>{
5308
+ waitLastCompileDoneResolve = resolve;
5309
+ }));
5310
+ });
5294
5311
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
5295
5312
  getPublicPathFromCompiler(compiler)
5296
5313
  ], compilationManager = new CompilationManager({
@@ -5348,19 +5365,19 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
5348
5365
  {
5349
5366
  getStats: async ()=>{
5350
5367
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getStats')} when ${picocolors.yellow('runCompile')} is false`);
5351
- return await waitFirstCompileDone, lastStats[environment.index];
5368
+ return await waitLastCompileDone, lastStats[environment.index];
5352
5369
  },
5353
5370
  context: environment,
5354
5371
  loadBundle: async (entryName)=>{
5355
5372
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('loadBundle')} when ${picocolors.yellow('runCompile')} is false`);
5356
- return await waitFirstCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5373
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
5357
5374
  readFileSync: compilationManager.readFileSync,
5358
5375
  environment
5359
5376
  });
5360
5377
  },
5361
5378
  getTransformedHtml: async (entryName)=>{
5362
5379
  if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getTransformedHtml')} when ${picocolors.yellow('runCompile')} is false`);
5363
- return await waitFirstCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5380
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
5364
5381
  readFileSync: compilationManager.readFileSync,
5365
5382
  environment
5366
5383
  });
@@ -7026,10 +7043,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
7026
7043
  },
7027
7044
  {
7028
7045
  name: 'rsbuild:lazy-compilation',
7046
+ apply: 'serve',
7029
7047
  setup (api) {
7030
- api.modifyBundlerChain((chain, { environment, isProd, target })=>{
7048
+ api.modifyBundlerChain((chain, { environment, target })=>{
7031
7049
  var _config_dev;
7032
- if (isProd || 'web' !== target) return;
7050
+ if ('web' !== target) return;
7033
7051
  let { config } = environment, options = null == (_config_dev = config.dev) ? void 0 : _config_dev.lazyCompilation;
7034
7052
  if (options) {
7035
7053
  if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.experiments({
@@ -7146,12 +7164,10 @@ async function createRsbuild(options = {}) {
7146
7164
  ...options,
7147
7165
  rsbuildConfig: config
7148
7166
  }, pluginManager = (plugins = [], {
7149
- getPlugins: (options = {
7150
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7151
- })=>plugins.filter((p)=>isPluginMatchEnvironment(p.environment, options.environment)).map((p)=>p.instance),
7167
+ getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
7152
7168
  getAllPluginsWithMeta: ()=>plugins,
7153
7169
  addPlugins: (newPlugins, options)=>{
7154
- let { before, environment = RSBUILD_ALL_ENVIRONMENT_SYMBOL } = options || {};
7170
+ let { before, environment } = options || {};
7155
7171
  for (let newPlugin of newPlugins)if (newPlugin) {
7156
7172
  let type = typeof newPlugin;
7157
7173
  if ('object' !== type || null === newPlugin) throw Error(`${picocolors.dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors.yellow(type)}.`);
@@ -7192,9 +7208,7 @@ async function createRsbuild(options = {}) {
7192
7208
  removePlugins: (pluginNames, options = {})=>{
7193
7209
  plugins = plugins.filter((plugin)=>!(pluginNames.includes(plugin.instance.name) && (!options.environment || plugin.environment === options.environment)));
7194
7210
  },
7195
- isPluginExists: (pluginName, options = {
7196
- environment: RSBUILD_ALL_ENVIRONMENT_SYMBOL
7197
- })=>!!plugins.find((plugin)=>plugin.instance.name === pluginName && isPluginMatchEnvironment(plugin.environment, options.environment))
7211
+ isPluginExists: (pluginName, options = {})=>plugins.some((plugin)=>plugin.instance.name === pluginName && isEnvironmentMatch(plugin.environment, options.environment))
7198
7212
  }), context = await createContext(resolvedOptions, config), getPluginAPI = function({ context, pluginManager }) {
7199
7213
  let { hooks } = context, publicContext = function(context) {
7200
7214
  let exposedKeys = [
@@ -7248,7 +7262,7 @@ async function createRsbuild(options = {}) {
7248
7262
  let pluginName = 'RsbuildCorePlugin';
7249
7263
  chain.plugin(pluginName).use(class {
7250
7264
  apply(compiler) {
7251
- for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7265
+ for (let { handler, environment: pluginEnvironment } of (compiler.__rsbuildTransformer = transformer, resolveFns))(!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compiler.hooks.compilation.tap(pluginName, (compilation, { normalModuleFactory })=>{
7252
7266
  normalModuleFactory.hooks.resolve.tapPromise(pluginName, async (resolveData)=>handler({
7253
7267
  compiler,
7254
7268
  compilation,
@@ -7261,7 +7275,7 @@ async function createRsbuild(options = {}) {
7261
7275
  childCompiler.__rsbuildTransformer = transformer;
7262
7276
  });
7263
7277
  let { sources } = compiler.webpack;
7264
- for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isPluginMatchEnvironment(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7278
+ for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
7265
7279
  name: pluginName,
7266
7280
  stage: mapProcessAssetsStage(compiler, descriptor.stage)
7267
7281
  }, async (assets)=>handler({
@@ -7672,11 +7686,11 @@ async function runCLI() {
7672
7686
  ].includes(level) && (logger.level = level);
7673
7687
  }
7674
7688
  let { npm_execpath } = process.env;
7675
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.7\n`);
7689
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.8\n`);
7676
7690
  try {
7677
7691
  !function() {
7678
7692
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7679
- cli.help(), cli.version("1.4.7"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7693
+ cli.help(), cli.version("1.4.8"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7680
7694
  default: 'jiti'
7681
7695
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7682
7696
  type: [
@@ -7734,5 +7748,5 @@ async function runCLI() {
7734
7748
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
7735
7749
  }
7736
7750
  }
7737
- let src_version = "1.4.7";
7751
+ let src_version = "1.4.8";
7738
7752
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, src_version as version };
@@ -23,7 +23,7 @@ export type LoadEnvOptions = {
23
23
  };
24
24
  export type LoadEnvResult = {
25
25
  /**
26
- * All env variables in the .env file
26
+ * All environment variables in the .env file
27
27
  */
28
28
  parsed: Record<string, string>;
29
29
  /**
@@ -31,7 +31,7 @@ export type LoadEnvResult = {
31
31
  */
32
32
  filePaths: string[];
33
33
  /**
34
- * Env variables that start with prefixes.
34
+ * Environment variables that start with prefixes.
35
35
  *
36
36
  * @example
37
37
  * ```ts
@@ -42,7 +42,7 @@ export type LoadEnvResult = {
42
42
  **/
43
43
  rawPublicVars: Record<string, string | undefined>;
44
44
  /**
45
- * Formatted env variables that start with prefixes.
45
+ * Formatted environment variables that start with prefixes.
46
46
  * The keys contain the prefixes `process.env.*` and `import.meta.env.*`.
47
47
  * The values are processed by `JSON.stringify`.
48
48
  *
@@ -56,7 +56,7 @@ export type LoadEnvResult = {
56
56
  **/
57
57
  publicVars: Record<string, string>;
58
58
  /**
59
- * Clear the env variables mounted on `process.env`
59
+ * Clear the environment variables mounted on `process.env`
60
60
  */
61
61
  cleanup: () => void;
62
62
  };
@@ -1,9 +1,12 @@
1
- import type { PluginManager, PluginMeta, RsbuildPluginAPI } from './types';
2
- export declare const RSBUILD_ALL_ENVIRONMENT_SYMBOL = "RSBUILD_ALL_ENVIRONMENT_SYMBOL";
3
- export declare const isPluginMatchEnvironment: (pluginEnvironment: string, currentEnvironment: string) => boolean;
1
+ import type { InternalContext, PluginManager, PluginMeta } from './types';
2
+ /**
3
+ * Determines whether the plugin is registered in the specified environment.
4
+ * If the pluginEnvironment is undefined, it means it can match any environment.
5
+ */
6
+ export declare const isEnvironmentMatch: (pluginEnvironment?: string, specifiedEnvironment?: string) => boolean;
4
7
  export declare function createPluginManager(): PluginManager;
5
8
  export declare const pluginDagSort: (plugins: PluginMeta[]) => PluginMeta[];
6
- export declare function initPlugins({ getPluginAPI, pluginManager, }: {
7
- getPluginAPI: (environment?: string) => RsbuildPluginAPI;
9
+ export declare function initPlugins({ context, pluginManager, }: {
10
+ context: InternalContext;
8
11
  pluginManager: PluginManager;
9
12
  }): Promise<void>;
@@ -6,7 +6,7 @@ import type { Logger } from '../logger';
6
6
  import type { ModifyRspackConfigUtils, NarrowedRspackConfig, NormalizedConfig, NormalizedEnvironmentConfig, RsbuildConfig, RspackMerge } from './config';
7
7
  import type { RsbuildContext } from './context';
8
8
  import type { EnvironmentContext, ModifyBundlerChainFn, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyHTMLFn, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn } from './hooks';
9
- import type { RsbuildInstance, RsbuildTarget } from './rsbuild';
9
+ import type { AddPluginsOptions, RsbuildInstance, RsbuildTarget } from './rsbuild';
10
10
  import type { Rspack } from './rspack';
11
11
  import type { HtmlRspackPlugin } from './thirdParty';
12
12
  import type { Falsy, MaybePromise } from './utils';
@@ -117,13 +117,14 @@ export type ModifyWebpackConfigUtils = ModifyWebpackChainUtils & {
117
117
  export type ModifyWebpackChainFn = (chain: RspackChain, utils: ModifyWebpackChainUtils) => Promise<void> | void;
118
118
  export type ModifyWebpackConfigFn = (config: WebpackConfig, utils: ModifyWebpackConfigUtils) => Promise<WebpackConfig | void> | WebpackConfig | void;
119
119
  export type PluginMeta = {
120
- environment: string;
120
+ environment?: AddPluginsOptions['environment'];
121
121
  instance: RsbuildPlugin;
122
122
  };
123
123
  export type PluginManager = Pick<RsbuildInstance, 'getPlugins' | 'addPlugins' | 'isPluginExists' | 'removePlugins'> & {
124
124
  /** Get all plugins with environment info */
125
125
  getAllPluginsWithMeta: () => PluginMeta[];
126
126
  };
127
+ export type RsbuildPluginApply = 'serve' | 'build';
127
128
  /**
128
129
  * The type of the Rsbuild plugin object.
129
130
  */
@@ -132,6 +133,13 @@ export type RsbuildPlugin = {
132
133
  * The name of the plugin, a unique identifier.
133
134
  */
134
135
  name: string;
136
+ /**
137
+ * Conditional apply the plugin during serve or build.
138
+ * - `'serve'`: Apply the plugin when starting the dev server or preview server.
139
+ * - `'build'`: Apply the plugin during build.
140
+ * - If not specified, the plugin will be applied during both serve and build.
141
+ */
142
+ apply?: RsbuildPluginApply;
135
143
  /**
136
144
  * The setup function of the plugin, which can be an async function.
137
145
  * This function is called once when the plugin is initialized.
@@ -135,7 +135,7 @@ export type CreateRsbuildOptions = {
135
135
  */
136
136
  rsbuildConfig?: RsbuildConfig | (() => Promise<RsbuildConfig>);
137
137
  /**
138
- * Whether to call `loadEnv` to load env variables and define them
138
+ * Whether to call `loadEnv` to load environment variables and define them
139
139
  * as global variables via `source.define`.
140
140
  * @default false
141
141
  */
@@ -158,23 +158,26 @@ export type RsbuildProvider<B extends 'rspack' | 'webpack' = 'rspack'> = (option
158
158
  rsbuildOptions: ResolvedCreateRsbuildOptions;
159
159
  helpers: RsbuildProviderHelpers;
160
160
  }) => Promise<ProviderInstance<B>>;
161
+ export type AddPluginsOptions = {
162
+ /**
163
+ * Insert before the specified plugin.
164
+ */
165
+ before?: string;
166
+ /**
167
+ * Specify the environment that the plugin will be applied to.
168
+ * If not specified, the plugin will be be registered as a global plugin and
169
+ * applied to all environments.
170
+ */
171
+ environment?: string;
172
+ };
173
+ export type AddPlugins = (plugins: Array<RsbuildPlugin | Falsy>, options?: AddPluginsOptions) => void;
161
174
  export type RsbuildInstance = {
162
175
  /**
163
176
  * Register one or more Rsbuild plugins, which can be called multiple times.
164
177
  * This method needs to be called before compiling. If it is called after
165
178
  * compiling, it will not affect the compilation result.
166
179
  */
167
- addPlugins: (plugins: Array<RsbuildPlugin | Falsy>, options?: {
168
- /**
169
- * Insert before the specified plugin.
170
- */
171
- before?: string;
172
- /**
173
- * Add a plugin for the specified environment.
174
- * If environment is not specified, it will be registered as a global plugin (effective in all environments)
175
- */
176
- environment?: string;
177
- }) => void;
180
+ addPlugins: AddPlugins;
178
181
  /**
179
182
  * Get all the Rsbuild plugins registered in the current Rsbuild instance.
180
183
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.4.7",
3
+ "version": "1.4.8",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.rs",
6
6
  "bugs": {
package/types.d.ts CHANGED
@@ -1,10 +1,27 @@
1
1
  /// <reference types="@rspack/core/module" />
2
2
 
3
+ /**
4
+ * This is a placeholder for extending the type options.
5
+ * You can augment this interface to enable stricter type checking.
6
+ * @example
7
+ * ```ts
8
+ * interface RsbuildTypeOptions {
9
+ * // This will enable strict type checking for `import.meta.env`.
10
+ * strictImportMetaEnv: true;
11
+ * }
12
+ * ```
13
+ */
14
+ // biome-ignore lint/suspicious/noEmptyInterface: placeholder
15
+ interface RsbuildTypeOptions {}
16
+
3
17
  /**
4
18
  * import.meta
5
19
  */
20
+ type ImportMetaEnvFallbackKey =
21
+ 'strictImportMetaEnv' extends keyof RsbuildTypeOptions ? never : string;
22
+
6
23
  interface ImportMetaEnv {
7
- [key: string]: any;
24
+ [key: ImportMetaEnvFallbackKey]: any;
8
25
  /**
9
26
  * The value of the `mode` configuration.
10
27
  * @example