@rsbuild/core 1.6.3 → 1.6.4

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.js CHANGED
@@ -3030,7 +3030,7 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
3030
3030
  await onEnvironmentDone(0, stats), await onDone(stats);
3031
3031
  });
3032
3032
  }, registerBuildHook = ({ context, isWatch, compiler, bundlerConfigs, MultiStatsCtor })=>{
3033
- let isFirstCompile = !0, environmentList = Object.values(context.environments).reduce((prev, curr)=>(prev[curr.index] = curr, prev), []), onDone = async (stats)=>{
3033
+ let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
3034
3034
  let p = context.hooks.onAfterBuild.callBatch({
3035
3035
  isFirstCompile,
3036
3036
  stats,
@@ -3078,7 +3078,7 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
3078
3078
  MultiStatsCtor
3079
3079
  });
3080
3080
  }, registerDevHook = ({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
3081
- let isFirstCompile = !0, environmentList = Object.values(context.environments).reduce((prev, curr)=>(prev[curr.index] = curr, prev), []), onDone = async (stats)=>{
3081
+ let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
3082
3082
  let p = context.hooks.onAfterDevCompile.callBatch({
3083
3083
  isFirstCompile,
3084
3084
  stats,
@@ -3185,11 +3185,18 @@ function hintUnknownFiles(message) {
3185
3185
  ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
3186
3186
  return message;
3187
3187
  }
3188
- function formatStatsError(stats, verbose) {
3189
- let message, fileName = resolveFileName(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = formatModuleTrace(stats, fileName) ?? '';
3190
- message = `${!fileName ? '' : /:\d+:\d+/.test(fileName) ? `File: ${color.cyan(fileName)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`}${mainMessage}${details}${stack}${moduleTrace}`;
3188
+ function formatStatsError(stats) {
3189
+ let fileName = resolveFileName(stats), message = `${!fileName ? '' : /:\d+:\d+/.test(fileName) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`}${stats.message}`, verbose = 'verbose' === logger.level;
3190
+ verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`));
3191
+ let moduleTrace = formatModuleTrace(stats, fileName);
3192
+ moduleTrace && (message += moduleTrace);
3191
3193
  let innerError = '-- inner error --';
3192
- return !verbose && message.includes(innerError) && (message = message.split(innerError)[0]), (message = (message = ((message)=>{
3194
+ !verbose && message.includes(innerError) && (message = message.split(innerError)[0]);
3195
+ let lines = (message = ((message)=>{
3196
+ if (-1 === message.indexOf('Multiple assets emit different content to the same filename')) return message;
3197
+ let extraMessage = `You may need to adjust ${color.yellow('output.filename')} configuration to prevent name conflicts. (See ${color.yellow('https://rsbuild.rs/config/output/filename')})`;
3198
+ return `${message}\n${extraMessage}`;
3199
+ })(message = ((message)=>{
3193
3200
  let getTips = (moduleName)=>{
3194
3201
  let tips = [
3195
3202
  `Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
@@ -3244,7 +3251,8 @@ function formatStatsError(stats, verbose) {
3244
3251
  'vm',
3245
3252
  'zlib'
3246
3253
  ].includes(moduleName) ? getTips(moduleName) : message;
3247
- })(message = hintUnknownFiles(message))).split('\n').filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim()).join('\n')).trim();
3254
+ })(message = hintUnknownFiles(message)))).split('\n');
3255
+ return (message = (lines = lines.filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim())).join('\n')).trim();
3248
3256
  }
3249
3257
  function formatErrorMessage(errors) {
3250
3258
  if (!errors.length) return 'Build failed. No errors reported since Rspack\'s "stats.errors" is disabled.';
@@ -3261,7 +3269,8 @@ function getStatsOptions(compiler, action) {
3261
3269
  timings: !0,
3262
3270
  errors: !0,
3263
3271
  warnings: !0,
3264
- moduleTrace: !0
3272
+ moduleTrace: !0,
3273
+ errorStack: 'verbose' === logger.level
3265
3274
  };
3266
3275
  if ('dev' === action && (defaultOptions = {
3267
3276
  ...defaultOptions,
@@ -3285,12 +3294,11 @@ function getRsbuildStats(statsInstance, compiler, action) {
3285
3294
  return statsInstance.toJson(statsOptions);
3286
3295
  }
3287
3296
  function formatStats(stats, hasErrors) {
3288
- let verbose = 'verbose' === logger.level;
3289
3297
  if (hasErrors) return {
3290
- message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item, verbose))),
3298
+ message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item))),
3291
3299
  level: 'error'
3292
3300
  };
3293
- let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, verbose));
3301
+ let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item));
3294
3302
  if (warningMessages.length) {
3295
3303
  let title = color.bold(color.yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
3296
3304
  return {
@@ -3534,8 +3542,8 @@ let OVERRIDE_PATHS = new Set([
3534
3542
  dev.watchFiles
3535
3543
  ]), normalizedConfig.dev = dev), normalizedConfig;
3536
3544
  }, mergeRsbuildConfig = (...originalConfigs)=>{
3537
- let configs = originalConfigs.map(normalizeConfigStructure);
3538
- return 2 === configs.length ? merge(configs[0], configs[1]) : configs.length < 2 ? configs[0] : configs.reduce((result, config)=>merge(result, config), {});
3545
+ let configs = originalConfigs.filter((config)=>void 0 !== config).map(normalizeConfigStructure);
3546
+ return 2 === configs.length ? merge(configs[0], configs[1]) : 1 === configs.length ? configs[0] : 0 === configs.length ? {} : configs.reduce((result, config)=>merge(result, config), {});
3539
3547
  }, defaultConfig_require = (0, external_node_module_.createRequire)(import.meta.url), defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, createDefaultConfig = ()=>({
3540
3548
  dev: {
3541
3549
  hmr: !0,
@@ -4114,15 +4122,15 @@ async function updateEnvironmentContext(context, configs) {
4114
4122
  tsconfigPath,
4115
4123
  config,
4116
4124
  webSocketToken
4117
- };
4118
- context.environments[name] = new Proxy(environmentContext, {
4125
+ }, readonlyEnvironmentContext = new Proxy(environmentContext, {
4119
4126
  get: (target, prop)=>target[prop],
4120
4127
  set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue : logger.error(`EnvironmentContext is readonly, you can not assign to the "environment.${prop}" prop.`), !0)
4121
4128
  });
4129
+ context.environmentList[index] = readonlyEnvironmentContext, context.environments[name] = readonlyEnvironmentContext;
4122
4130
  }
4123
4131
  }
4124
4132
  function updateContextByNormalizedConfig(context) {
4125
- let distPaths = Object.values(context.environments).map((item)=>item.distPath);
4133
+ let distPaths = context.environmentList.map((item)=>item.distPath);
4126
4134
  context.distPath = getCommonParentPath(distPaths);
4127
4135
  }
4128
4136
  function createPublicContext(context) {
@@ -4146,13 +4154,14 @@ function createPublicContext(context) {
4146
4154
  async function createContext(options, userConfig) {
4147
4155
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
4148
4156
  return {
4149
- version: "1.6.3",
4157
+ version: "1.6.4",
4150
4158
  rootPath,
4151
4159
  distPath: '',
4152
4160
  cachePath,
4153
4161
  callerName: options.callerName,
4154
4162
  bundlerType,
4155
4163
  environments: {},
4164
+ environmentList: [],
4156
4165
  publicPathnames: [],
4157
4166
  hooks: initHooks(),
4158
4167
  config: {
@@ -4454,10 +4463,11 @@ function getConfigUtils(getCurrentConfig, chainUtils) {
4454
4463
  }
4455
4464
  };
4456
4465
  }
4457
- function getChainUtils(target, environment) {
4466
+ function getChainUtils(target, environment, environments) {
4458
4467
  return {
4459
4468
  rspack: rspack_rspack,
4460
4469
  environment,
4470
+ environments,
4461
4471
  env: process.env.NODE_ENV || '',
4462
4472
  target,
4463
4473
  isDev: 'development' === environment.config.mode,
@@ -4477,8 +4487,8 @@ function validateRspackConfig(config) {
4477
4487
  }
4478
4488
  config.devServer && logger.warn(`${color.dim('[rsbuild:config]')} Find invalid Rspack config: "${color.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`);
4479
4489
  }
4480
- async function generateRspackConfig({ target, context, environment }) {
4481
- let chainUtils = getChainUtils(target, context.environments[environment]), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
4490
+ async function generateRspackConfig({ target, context, environmentName }) {
4491
+ let chainUtils = getChainUtils(target, context.environments[environmentName], context.environments), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
4482
4492
  ...chainUtils,
4483
4493
  bundler: {
4484
4494
  BannerPlugin,
@@ -4627,10 +4637,10 @@ async function initConfigs({ context, pluginManager, rsbuildOptions }) {
4627
4637
  let normalizedConfig = await initRsbuildConfig({
4628
4638
  context,
4629
4639
  pluginManager
4630
- }), rspackConfigs = await Promise.all(Object.entries(normalizedConfig.environments).map(([environment, config])=>generateRspackConfig({
4640
+ }), rspackConfigs = await Promise.all(Object.entries(normalizedConfig.environments).map(([environmentName, config])=>generateRspackConfig({
4631
4641
  target: config.output.target,
4632
4642
  context,
4633
- environment
4643
+ environmentName
4634
4644
  })));
4635
4645
  if (isDebug()) {
4636
4646
  let inspect = async ()=>{
@@ -4734,8 +4744,8 @@ async function createCompiler_createCompiler(options) {
4734
4744
  logger.ready(`built in ${time}${suffix}`);
4735
4745
  }
4736
4746
  };
4737
- hasErrors || (isMultiCompiler && stats.children?.length ? stats.children.forEach((c, index)=>{
4738
- printTime(c, index);
4747
+ hasErrors || (isMultiCompiler && stats.children?.length ? stats.children.forEach((item, index)=>{
4748
+ printTime(item, index);
4739
4749
  }) : printTime(stats, 0));
4740
4750
  let { message, level } = formatStats(stats, hasErrors);
4741
4751
  'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
@@ -5450,7 +5460,7 @@ let getInlineTests = (config)=>{
5450
5460
  let trailingSlashBase = addTrailingSlash(base);
5451
5461
  return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
5452
5462
  }, getRoutes = (context)=>{
5453
- let environmentWithHtml = Object.values(context.environments).filter((item)=>Object.keys(item.htmlPaths).length > 0);
5463
+ let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
5454
5464
  if (0 === environmentWithHtml.length) return [];
5455
5465
  let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
5456
5466
  return environmentWithHtml.reduce((prev, environmentContext)=>{
@@ -6195,7 +6205,7 @@ async function getFileFromUrl(url, outputFileSystem, context) {
6195
6205
  outputFileSystem.stat(filename, (err, stats)=>{
6196
6206
  err ? reject(err) : resolve(stats);
6197
6207
  });
6198
- }), { environments, publicPathnames } = context, distPaths = Object.values(environments).map((env)=>env.distPath), possibleFilenames = new Set();
6208
+ }), { environmentList, publicPathnames } = context, distPaths = environmentList.map((env)=>env.distPath), possibleFilenames = new Set();
6199
6209
  for (let [index, distPath] of distPaths.entries()){
6200
6210
  let prefix = publicPathnames[index];
6201
6211
  prefix && '/' !== prefix && pathname.startsWith(prefix) && possibleFilenames.add(external_node_path_.default.join(distPath, pathname.slice(prefix.length)));
@@ -6519,9 +6529,9 @@ function applyHMREntry({ config, compiler, token, resolvedHost, resolvedPort })
6519
6529
  }
6520
6530
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6521
6531
  var config1;
6522
- let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments } = context;
6532
+ let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments, environmentList } = context;
6523
6533
  applyToCompiler(compiler, (compiler, index)=>{
6524
- let environment = Object.values(environments).find((env)=>env.index === index);
6534
+ let environment = environmentList[index];
6525
6535
  if (!environment) return;
6526
6536
  let token = environment.webSocketToken;
6527
6537
  token && (applyHMREntry({
@@ -6575,7 +6585,7 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6575
6585
  }), callbacks.length = 0);
6576
6586
  });
6577
6587
  });
6578
- let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6588
+ let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = environmentList.map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6579
6589
  let { writeToDisk } = config1;
6580
6590
  return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6581
6591
  });
@@ -6953,7 +6963,7 @@ class SocketServer {
6953
6963
  upgrade = (req, socket, head)=>{
6954
6964
  if (!this.wsServer.shouldHandle(req)) return;
6955
6965
  let query = parseQueryString(req);
6956
- Object.values(this.context.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6966
+ this.context.environmentList.map(({ webSocketToken })=>webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6957
6967
  this.wsServer.emit('connection', connection, req);
6958
6968
  }) : socket.destroy();
6959
6969
  };
@@ -7034,7 +7044,7 @@ class SocketServer {
7034
7044
  });
7035
7045
  }
7036
7046
  getStats(token) {
7037
- let { stats } = this.context.buildState, environment = Object.values(this.context.environments).find(({ webSocketToken })=>webSocketToken === token);
7047
+ let { stats } = this.context.buildState, environment = this.context.environmentList.find(({ webSocketToken })=>webSocketToken === token);
7038
7048
  if (!stats || !environment) return;
7039
7049
  let currentStats = stats;
7040
7050
  if (stats.children) {
@@ -7765,30 +7775,31 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7765
7775
  if (!htmlPath) throw Error(`${color.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${color.yellow(entryName)}`);
7766
7776
  let fileName = (0, external_node_path_.join)(distPath, htmlPath);
7767
7777
  return utils.readFileSync(fileName);
7768
- })(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
7769
- name,
7770
- {
7771
- getStats: async ()=>{
7772
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getStats')} when ${color.yellow('runCompile')} is false`);
7773
- return await waitLastCompileDone, lastStats[environment.index];
7774
- },
7775
- context: environment,
7776
- loadBundle: async (entryName)=>{
7777
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('loadBundle')} when ${color.yellow('runCompile')} is false`);
7778
- return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
7779
- readFileSync: buildManager.readFileSync,
7780
- environment
7781
- });
7782
- },
7783
- getTransformedHtml: async (entryName)=>{
7784
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getTransformedHtml')} when ${color.yellow('runCompile')} is false`);
7785
- return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
7786
- readFileSync: buildManager.readFileSync,
7787
- environment
7788
- });
7789
- }
7778
+ })(entryName, utils)), environmentAPI = {}, getErrorMsg = (method)=>`${color.dim('[rsbuild:server]')} Can not call ${color.yellow(method)} when ${color.yellow('runCompile')} is false`;
7779
+ context.environmentList.forEach((environment, index)=>{
7780
+ environmentAPI[environment.name] = {
7781
+ context: environment,
7782
+ getStats: async ()=>{
7783
+ if (!buildManager) throw Error(getErrorMsg('getStats'));
7784
+ return await waitLastCompileDone, lastStats[index];
7785
+ },
7786
+ loadBundle: async (entryName)=>{
7787
+ if (!buildManager) throw Error(getErrorMsg('loadBundle'));
7788
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[index], entryName, {
7789
+ readFileSync: buildManager.readFileSync,
7790
+ environment
7791
+ });
7792
+ },
7793
+ getTransformedHtml: async (entryName)=>{
7794
+ if (!buildManager) throw Error(getErrorMsg('getTransformedHtml'));
7795
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[index], entryName, {
7796
+ readFileSync: buildManager.readFileSync,
7797
+ environment
7798
+ });
7790
7799
  }
7791
- ])), middlewares = requireCompiledPackage('connect')(), httpServer = middlewareMode ? null : await createHttpServer({
7800
+ };
7801
+ });
7802
+ let middlewares = requireCompiledPackage('connect')(), httpServer = middlewareMode ? null : await createHttpServer({
7792
7803
  serverConfig: config.server,
7793
7804
  middlewares
7794
7805
  }), devServerAPI = {
@@ -8125,7 +8136,7 @@ class RsbuildProdServer {
8125
8136
  ],
8126
8137
  single: 'index' === htmlFallback
8127
8138
  });
8128
- this.middlewares.use((req, res, next)=>{
8139
+ this.middlewares.use(function staticAssetMiddleware(req, res, next) {
8129
8140
  let url = req.url, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
8130
8141
  assetPrefix && url?.startsWith(assetPrefix) ? (req.url = url.slice(assetPrefix.length), assetsMiddleware(req, res, (...args)=>{
8131
8142
  req.url = url, next(...args);
@@ -8141,7 +8152,7 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
8141
8152
  pwd: context.rootPath,
8142
8153
  output: {
8143
8154
  path: context.distPath,
8144
- assetPrefixes: Object.values(context.environments).map((e)=>getPathnameFromUrl(e.config.output.assetPrefix))
8155
+ assetPrefixes: context.environmentList.map((e)=>getPathnameFromUrl(e.config.output.assetPrefix))
8145
8156
  },
8146
8157
  serverConfig
8147
8158
  }, middlewares);
@@ -8806,7 +8817,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8806
8817
  let postcssrcCache = new Map();
8807
8818
  api.modifyBundlerChain({
8808
8819
  order: 'pre',
8809
- handler: async (chain, { target, isProd, CHAIN_ID, environment })=>{
8820
+ handler: async (chain, { target, isProd, CHAIN_ID, environment, environments })=>{
8810
8821
  let rule = chain.module.rule(CHAIN_ID.RULE.CSS), inlineRule = chain.module.rule(CHAIN_ID.RULE.CSS_INLINE), { config } = environment;
8811
8822
  rule.test(CSS_REGEX).type("javascript/auto").dependency({
8812
8823
  not: 'url'
@@ -8825,34 +8836,43 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8825
8836
  rule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
8826
8837
  } else rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader((cssExtractPlugin || rspack_rspack.CssExtractRspackPlugin).loader).options(config.tools.cssExtract.loaderOptions);
8827
8838
  else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(external_node_path_.default.join(LOADER_PATH, 'ignoreCssLoader.mjs'));
8828
- let importLoaders = 0, updateRules = (callback)=>{
8829
- callback(rule, 'normal'), callback(inlineRule, 'inline');
8839
+ let importLoaders = {
8840
+ normal: 0,
8841
+ inline: 0
8842
+ }, updateRules = (callback, options = {})=>{
8843
+ options.skipNormal || callback(rule, 'normal'), callback(inlineRule, 'inline');
8830
8844
  }, cssLoaderPath = getCompiledPath('css-loader');
8831
8845
  if (updateRules((rule)=>{
8832
8846
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
8833
- }), emitCss) {
8834
- if ('rspack' === api.context.bundlerType && !1 !== config.tools.lightningcssLoader) {
8835
- importLoaders++;
8836
- let { minifyCss } = parseMinifyOptions(config);
8837
- updateRules((rule, type)=>{
8838
- let inlineStyle = 'inline' === type || config.output.injectStyles, lightningcssOptions = getLightningCSSLoaderOptions(config, environment.browserslist, inlineStyle && minifyCss);
8839
- rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
8840
- });
8847
+ }), 'rspack' === api.context.bundlerType && !1 !== config.tools.lightningcssLoader) {
8848
+ emitCss && importLoaders.normal++, importLoaders.inline++;
8849
+ let { minifyCss } = parseMinifyOptions(config), { browserslist } = environment;
8850
+ if ('node' === target) {
8851
+ let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
8852
+ webEnvironment?.browserslist && (browserslist = webEnvironment.browserslist);
8841
8853
  }
8842
- let postcssLoaderOptions = await getPostcssLoaderOptions({
8843
- config,
8844
- root: api.context.rootPath,
8845
- postcssrcCache
8854
+ updateRules((rule, type)=>{
8855
+ let inlineStyle = 'inline' === type || config.output.injectStyles, lightningcssOptions = getLightningCSSLoaderOptions(config, browserslist, inlineStyle && minifyCss);
8856
+ rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
8857
+ }, {
8858
+ skipNormal: !emitCss
8846
8859
  });
8847
- if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
8848
- importLoaders++;
8849
- let postcssLoaderPath = getCompiledPath('postcss-loader');
8850
- updateRules((rule)=>{
8851
- rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
8852
- });
8853
- }
8854
8860
  }
8855
- let localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = (({ config, importLoaders, localIdentName, emitCss })=>{
8861
+ let postcssLoaderOptions = await getPostcssLoaderOptions({
8862
+ config,
8863
+ root: api.context.rootPath,
8864
+ postcssrcCache
8865
+ });
8866
+ if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
8867
+ emitCss && importLoaders.normal++, importLoaders.inline++;
8868
+ let postcssLoaderPath = getCompiledPath('postcss-loader');
8869
+ updateRules((rule)=>{
8870
+ rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
8871
+ }, {
8872
+ skipNormal: !emitCss
8873
+ });
8874
+ }
8875
+ let localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = (({ config, localIdentName, emitCss })=>{
8856
8876
  let { cssModules } = config.output;
8857
8877
  return ((options, exportOnlyLocals)=>{
8858
8878
  if (options.modules && exportOnlyLocals) {
@@ -8873,7 +8893,6 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8873
8893
  return options;
8874
8894
  })(reduceConfigs({
8875
8895
  initial: {
8876
- importLoaders,
8877
8896
  modules: {
8878
8897
  ...cssModules,
8879
8898
  localIdentName
@@ -8885,16 +8904,20 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8885
8904
  }), !emitCss);
8886
8905
  })({
8887
8906
  config,
8888
- importLoaders,
8889
8907
  localIdentName,
8890
8908
  emitCss
8891
8909
  });
8892
8910
  updateRules((rule, type)=>{
8893
- rule.use(CHAIN_ID.USE.CSS).options('inline' === type ? {
8911
+ let finalOptions = cssLoaderOptions;
8912
+ finalOptions = 'inline' === type ? {
8894
8913
  ...cssLoaderOptions,
8895
8914
  exportType: 'string',
8896
- modules: !1
8897
- } : cssLoaderOptions), rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8915
+ modules: !1,
8916
+ importLoaders: importLoaders.inline
8917
+ } : {
8918
+ ...cssLoaderOptions,
8919
+ importLoaders: importLoaders.normal
8920
+ }, rule.use(CHAIN_ID.USE.CSS).options(finalOptions), rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8898
8921
  });
8899
8922
  let isStringExport = 'string' === cssLoaderOptions.exportType;
8900
8923
  if (isStringExport && rule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && rule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), emitCss && !config.output.injectStyles && !isStringExport) {
@@ -9452,10 +9475,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9452
9475
  name: 'rsbuild:nonce',
9453
9476
  setup (api) {
9454
9477
  api.onAfterCreateCompiler(({ compiler, environments })=>{
9455
- let environmentList = Object.values(environments), nonces = environmentList.map((environment)=>{
9456
- let { nonce } = environment.config.security;
9457
- return nonce;
9458
- });
9478
+ let environmentList = Object.values(environments), nonces = Object.values(environments).map((environment)=>environment.config.security.nonce);
9459
9479
  nonces.some((nonce)=>!!nonce) && applyToCompiler(compiler, (compiler, index)=>{
9460
9480
  let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
9461
9481
  if (!Object.keys(environment?.htmlPaths ?? {}).length || !nonce) return;
@@ -9781,7 +9801,7 @@ let applyServerOptions = (command)=>{
9781
9801
  };
9782
9802
  function setupCommands() {
9783
9803
  let cli = ((name = "")=>new CAC(name))('rsbuild');
9784
- cli.version("1.6.3"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
9804
+ cli.version("1.6.4"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
9785
9805
  default: 'auto'
9786
9806
  }).option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
9787
9807
  type: [
@@ -9850,7 +9870,7 @@ function initNodeEnv() {
9850
9870
  }
9851
9871
  function showGreeting() {
9852
9872
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9853
- logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.6.3\n`);
9873
+ logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.6.4\n`);
9854
9874
  }
9855
9875
  function setupLogLevel() {
9856
9876
  let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
@@ -9871,7 +9891,7 @@ function runCLI() {
9871
9891
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
9872
9892
  }
9873
9893
  }
9874
- let src_version = "1.6.3";
9894
+ let src_version = "1.6.4";
9875
9895
  import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
9876
9896
  import { fileURLToPath as __webpack_fileURLToPath__ } from "node:url";
9877
9897
  import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module";
@@ -1,2 +1,2 @@
1
1
  import type { StatsError } from '@rspack/core';
2
- export declare function formatStatsError(stats: StatsError, verbose?: boolean): string;
2
+ export declare function formatStatsError(stats: StatsError): string;
@@ -1,2 +1,2 @@
1
1
  import type { RsbuildConfig } from './types';
2
- export declare const mergeRsbuildConfig: <T = RsbuildConfig>(...originalConfigs: T[]) => T;
2
+ export declare const mergeRsbuildConfig: <T = RsbuildConfig>(...originalConfigs: (T | undefined)[]) => T;
@@ -1,8 +1,8 @@
1
1
  import type { EnvironmentContext, InternalContext, ModifyChainUtils, ModifyRspackConfigUtils, RsbuildTarget, Rspack } from '../types';
2
2
  export declare function getConfigUtils(getCurrentConfig: () => Rspack.Configuration, chainUtils: ModifyChainUtils): ModifyRspackConfigUtils;
3
- export declare function getChainUtils(target: RsbuildTarget, environment: EnvironmentContext): ModifyChainUtils;
4
- export declare function generateRspackConfig({ target, context, environment, }: {
5
- environment: string;
3
+ export declare function getChainUtils(target: RsbuildTarget, environment: EnvironmentContext, environments: Record<string, EnvironmentContext>): ModifyChainUtils;
4
+ export declare function generateRspackConfig({ target, context, environmentName, }: {
6
5
  target: RsbuildTarget;
7
6
  context: InternalContext;
7
+ environmentName: string;
8
8
  }): Promise<Rspack.Configuration>;
@@ -11,5 +11,5 @@ export type ResolvedWriteToDisk = boolean | ((filePath: string, name?: string) =
11
11
  * Returns the unified config if all environments have the same value,
12
12
  * otherwise returns a function that resolves config based on compilation.
13
13
  */
14
- export declare const resolveWriteToDiskConfig: (config: NormalizedDevConfig, environments: Record<string, EnvironmentContext>) => ResolvedWriteToDisk;
14
+ export declare const resolveWriteToDiskConfig: (config: NormalizedDevConfig, environments: Record<string, EnvironmentContext>, environmentList: EnvironmentContext[]) => ResolvedWriteToDisk;
15
15
  export declare function setupWriteToDisk(compilers: Compiler[], writeToDisk: ResolvedWriteToDisk): void;
@@ -411,7 +411,15 @@ export interface ServerConfig {
411
411
  * - object: enable CORS with the specified options.
412
412
  * - true: enable CORS with default options (allow all origins, not recommended).
413
413
  * - false: disable CORS.
414
- * @default false
414
+ * @default
415
+ * ```js
416
+ * { origin: defaultAllowedOrigins }
417
+ * ```
418
+ * where `defaultAllowedOrigins` includes:
419
+ * - `localhost`
420
+ * - `127.0.0.1`
421
+ * - `[::1]`
422
+ *
415
423
  * @link https://github.com/expressjs/cors
416
424
  */
417
425
  cors?: boolean | cors.CorsOptions;
@@ -90,8 +90,10 @@ export type InternalContext = RsbuildContext & {
90
90
  * can be used in all environments.
91
91
  */
92
92
  getPluginAPI?: (environment?: string) => RsbuildPluginAPI;
93
- /** The environment context. */
93
+ /** Context information for all environments. */
94
94
  environments: Record<string, EnvironmentContext>;
95
+ /** Array of all environments. */
96
+ environmentList: EnvironmentContext[];
95
97
  /** Only build specified environment. */
96
98
  specifiedEnvironments?: string[];
97
99
  /** Build state information */
@@ -17,10 +17,16 @@ export type OnBeforeEnvironmentCompileFn<B = 'rspack'> = (params: CompileCommonP
17
17
  }) => MaybePromise<void>;
18
18
  export type OnCloseBuildFn = () => MaybePromise<void>;
19
19
  export type OnBeforeBuildFn<B = 'rspack'> = (params: CompileCommonParams & {
20
+ /**
21
+ * Context information for all environments.
22
+ */
20
23
  environments: Record<string, EnvironmentContext>;
21
24
  bundlerConfigs?: B extends 'rspack' ? Rspack.Configuration[] : WebpackConfig[];
22
25
  }) => MaybePromise<void>;
23
26
  export type OnBeforeDevCompileFn<B = 'rspack'> = (params: CompileCommonParams & {
27
+ /**
28
+ * Context information for all environments.
29
+ */
24
30
  environments: Record<string, EnvironmentContext>;
25
31
  bundlerConfigs?: B extends 'rspack' ? Rspack.Configuration[] : WebpackConfig[];
26
32
  }) => MaybePromise<void>;
@@ -30,12 +36,18 @@ export type OnAfterEnvironmentCompileFn = (params: CompileCommonParams & {
30
36
  }) => MaybePromise<void>;
31
37
  export type OnAfterBuildFn = (params: CompileCommonParams & {
32
38
  stats?: Rspack.Stats | Rspack.MultiStats;
39
+ /**
40
+ * Context information for all environments.
41
+ */
33
42
  environments: Record<string, EnvironmentContext>;
34
43
  }) => MaybePromise<void>;
35
44
  export type OnCloseDevServerFn = () => MaybePromise<void>;
36
45
  export type OnAfterDevCompileFn = (params: {
37
46
  isFirstCompile: boolean;
38
47
  stats: Rspack.Stats | Rspack.MultiStats;
48
+ /**
49
+ * Context information for all environments.
50
+ */
39
51
  environments: Record<string, EnvironmentContext>;
40
52
  }) => MaybePromise<void>;
41
53
  /**
@@ -48,7 +60,7 @@ export type OnBeforeStartDevServerFn = (params: {
48
60
  */
49
61
  server: RsbuildDevServer;
50
62
  /**
51
- * A read-only object that provides some context information about different environments.
63
+ * Context information for all environments.
52
64
  */
53
65
  environments: Record<string, EnvironmentContext>;
54
66
  }) => MaybePromise<(() => void) | void>;
@@ -60,19 +72,31 @@ export type Routes = {
60
72
  export type OnAfterStartDevServerFn = (params: {
61
73
  port: number;
62
74
  routes: Routes;
75
+ /**
76
+ * Context information for all environments.
77
+ */
63
78
  environments: Record<string, EnvironmentContext>;
64
79
  }) => MaybePromise<void>;
65
80
  export type OnAfterStartProdServerFn = (params: {
66
81
  port: number;
67
82
  routes: Routes;
83
+ /**
84
+ * Context information for all environments.
85
+ */
68
86
  environments: Record<string, EnvironmentContext>;
69
87
  }) => MaybePromise<void>;
70
88
  export type OnBeforeCreateCompilerFn<B = 'rspack'> = (params: {
71
89
  bundlerConfigs: B extends 'rspack' ? Rspack.Configuration[] : WebpackConfig[];
90
+ /**
91
+ * Context information for all environments.
92
+ */
72
93
  environments: Record<string, EnvironmentContext>;
73
94
  }) => MaybePromise<void>;
74
95
  export type OnAfterCreateCompilerFn<Compiler = Rspack.Compiler | Rspack.MultiCompiler> = (params: {
75
96
  compiler: Compiler;
97
+ /**
98
+ * Context information for all environments.
99
+ */
76
100
  environments: Record<string, EnvironmentContext>;
77
101
  }) => MaybePromise<void>;
78
102
  export type OnExitFn = (context: {
@@ -124,6 +148,9 @@ export type ModifyEnvironmentConfigUtils = {
124
148
  export type ModifyRsbuildConfigFn = (config: RsbuildConfig, utils: ModifyRsbuildConfigUtils) => MaybePromise<RsbuildConfig | void>;
125
149
  export type ModifyEnvironmentConfigFn = (config: MergedEnvironmentConfig, utils: ModifyEnvironmentConfigUtils) => MaybePromise<MergedEnvironmentConfig | void>;
126
150
  export type EnvironmentContext = {
151
+ /**
152
+ * The index of the current environment.
153
+ */
127
154
  index: number;
128
155
  /**
129
156
  * The unique name of the current environment is used to distinguish and locate the
@@ -209,6 +236,10 @@ export type ModifyChainUtils = {
209
236
  * The environment context for current build.
210
237
  */
211
238
  environment: EnvironmentContext;
239
+ /**
240
+ * Context information for all environments.
241
+ */
242
+ environments: Record<string, EnvironmentContext>;
212
243
  /**
213
244
  * The Rspack instance, same as `import { rspack } from '@rsbuild/core'`.
214
245
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "1.6.3",
3
+ "version": "1.6.4",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.rs",
6
6
  "bugs": {
@@ -46,7 +46,7 @@
46
46
  "types.d.ts"
47
47
  ],
48
48
  "dependencies": {
49
- "@rspack/core": "1.6.1",
49
+ "@rspack/core": "1.6.2",
50
50
  "@rspack/lite-tapable": "~1.0.1",
51
51
  "@swc/helpers": "^0.5.17",
52
52
  "core-js": "~3.46.0",