@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.cjs CHANGED
@@ -3072,7 +3072,7 @@ ${section.body}` : section.body).join("\n\n"));
3072
3072
  await onEnvironmentDone(0, stats), await onDone(stats);
3073
3073
  });
3074
3074
  }, registerBuildHook = ({ context, isWatch, compiler, bundlerConfigs, MultiStatsCtor })=>{
3075
- let isFirstCompile = !0, environmentList = Object.values(context.environments).reduce((prev, curr)=>(prev[curr.index] = curr, prev), []), onDone = async (stats)=>{
3075
+ let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
3076
3076
  let p = context.hooks.onAfterBuild.callBatch({
3077
3077
  isFirstCompile,
3078
3078
  stats,
@@ -3120,7 +3120,7 @@ ${section.body}` : section.body).join("\n\n"));
3120
3120
  MultiStatsCtor
3121
3121
  });
3122
3122
  }, registerDevHook = ({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
3123
- let isFirstCompile = !0, environmentList = Object.values(context.environments).reduce((prev, curr)=>(prev[curr.index] = curr, prev), []), onDone = async (stats)=>{
3123
+ let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
3124
3124
  let p = context.hooks.onAfterDevCompile.callBatch({
3125
3125
  isFirstCompile,
3126
3126
  stats,
@@ -3227,12 +3227,19 @@ ${section.body}` : section.body).join("\n\n"));
3227
3227
  ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
3228
3228
  return message;
3229
3229
  }
3230
- function formatStatsError(stats, verbose) {
3231
- var fileName;
3232
- let message, fileName1 = resolveFileName(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = formatModuleTrace(stats, fileName1) ?? '';
3233
- message = `${!(fileName = fileName1) ? '' : /:\d+:\d+/.test(fileName) ? `File: ${color.cyan(fileName)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`}${mainMessage}${details}${stack}${moduleTrace}`;
3230
+ function formatStatsError(stats) {
3231
+ var fileName, stats1;
3232
+ let fileName1 = resolveFileName(stats), message = `${(fileName = fileName1, stats1 = stats, !fileName ? '' : /:\d+:\d+/.test(fileName) ? `File: ${color.cyan(fileName)}\n` : stats1.loc ? `File: ${color.cyan(`${fileName}:${stats1.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`)}${stats.message}`, verbose = 'verbose' === logger.level;
3233
+ verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`));
3234
+ let moduleTrace = formatModuleTrace(stats, fileName1);
3235
+ moduleTrace && (message += moduleTrace);
3234
3236
  let innerError = '-- inner error --';
3235
- return !verbose && message.includes(innerError) && (message = message.split(innerError)[0]), (message = (message = ((message)=>{
3237
+ !verbose && message.includes(innerError) && (message = message.split(innerError)[0]);
3238
+ let lines = (message = ((message)=>{
3239
+ if (-1 === message.indexOf('Multiple assets emit different content to the same filename')) return message;
3240
+ 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')})`;
3241
+ return `${message}\n${extraMessage}`;
3242
+ })(message = ((message)=>{
3236
3243
  let getTips = (moduleName)=>{
3237
3244
  let tips = [
3238
3245
  `Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
@@ -3287,7 +3294,8 @@ ${section.body}` : section.body).join("\n\n"));
3287
3294
  'vm',
3288
3295
  'zlib'
3289
3296
  ].includes(moduleName) ? getTips(moduleName) : message;
3290
- })(message = hintUnknownFiles(message))).split('\n').filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim()).join('\n')).trim();
3297
+ })(message = hintUnknownFiles(message)))).split('\n');
3298
+ return (message = (lines = lines.filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim())).join('\n')).trim();
3291
3299
  }
3292
3300
  function formatErrorMessage(errors) {
3293
3301
  if (!errors.length) return 'Build failed. No errors reported since Rspack\'s "stats.errors" is disabled.';
@@ -3304,7 +3312,8 @@ ${section.body}` : section.body).join("\n\n"));
3304
3312
  timings: !0,
3305
3313
  errors: !0,
3306
3314
  warnings: !0,
3307
- moduleTrace: !0
3315
+ moduleTrace: !0,
3316
+ errorStack: 'verbose' === logger.level
3308
3317
  };
3309
3318
  if ('dev' === action && (defaultOptions = {
3310
3319
  ...defaultOptions,
@@ -3328,12 +3337,11 @@ ${section.body}` : section.body).join("\n\n"));
3328
3337
  return statsInstance.toJson(statsOptions);
3329
3338
  }
3330
3339
  function formatStats(stats, hasErrors) {
3331
- let verbose = 'verbose' === logger.level;
3332
3340
  if (hasErrors) return {
3333
- message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item, verbose))),
3341
+ message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item))),
3334
3342
  level: 'error'
3335
3343
  };
3336
- let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, verbose));
3344
+ let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item));
3337
3345
  if (warningMessages.length) {
3338
3346
  let title = color.bold(color.yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
3339
3347
  return {
@@ -3577,8 +3585,8 @@ ${section.body}` : section.body).join("\n\n"));
3577
3585
  dev.watchFiles
3578
3586
  ]), normalizedConfig.dev = dev), normalizedConfig;
3579
3587
  }, mergeRsbuildConfig = (...originalConfigs)=>{
3580
- let configs = originalConfigs.map(normalizeConfigStructure);
3581
- return 2 === configs.length ? merge(configs[0], configs[1]) : configs.length < 2 ? configs[0] : configs.reduce((result, config)=>merge(result, config), {});
3588
+ let configs = originalConfigs.filter((config)=>void 0 !== config).map(normalizeConfigStructure);
3589
+ return 2 === configs.length ? merge(configs[0], configs[1]) : 1 === configs.length ? configs[0] : 0 === configs.length ? {} : configs.reduce((result, config)=>merge(result, config), {});
3582
3590
  }, defaultConfig_require = (0, external_node_module_.createRequire)(__rslib_import_meta_url__), defaultAllowedOrigins = /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/, createDefaultConfig = ()=>({
3583
3591
  dev: {
3584
3592
  hmr: !0,
@@ -4181,15 +4189,15 @@ ${section.body}` : section.body).join("\n\n"));
4181
4189
  tsconfigPath,
4182
4190
  config,
4183
4191
  webSocketToken
4184
- };
4185
- context.environments[name] = new Proxy(environmentContext, {
4192
+ }, readonlyEnvironmentContext = new Proxy(environmentContext, {
4186
4193
  get: (target, prop)=>target[prop],
4187
4194
  set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue : logger.error(`EnvironmentContext is readonly, you can not assign to the "environment.${prop}" prop.`), !0)
4188
4195
  });
4196
+ context.environmentList[index] = readonlyEnvironmentContext, context.environments[name] = readonlyEnvironmentContext;
4189
4197
  }
4190
4198
  }
4191
4199
  function updateContextByNormalizedConfig(context) {
4192
- let distPaths = Object.values(context.environments).map((item)=>item.distPath);
4200
+ let distPaths = context.environmentList.map((item)=>item.distPath);
4193
4201
  context.distPath = getCommonParentPath(distPaths);
4194
4202
  }
4195
4203
  function createPublicContext(context) {
@@ -4213,13 +4221,14 @@ ${section.body}` : section.body).join("\n\n"));
4213
4221
  async function createContext(options, userConfig) {
4214
4222
  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';
4215
4223
  return {
4216
- version: "1.6.3",
4224
+ version: "1.6.4",
4217
4225
  rootPath,
4218
4226
  distPath: '',
4219
4227
  cachePath,
4220
4228
  callerName: options.callerName,
4221
4229
  bundlerType,
4222
4230
  environments: {},
4231
+ environmentList: [],
4223
4232
  publicPathnames: [],
4224
4233
  hooks: initHooks(),
4225
4234
  config: {
@@ -4524,10 +4533,11 @@ ${section.body}` : section.body).join("\n\n"));
4524
4533
  }
4525
4534
  };
4526
4535
  }
4527
- function getChainUtils(target, environment) {
4536
+ function getChainUtils(target, environment, environments) {
4528
4537
  return {
4529
4538
  rspack: rspack_rspack,
4530
4539
  environment,
4540
+ environments,
4531
4541
  env: process.env.NODE_ENV || '',
4532
4542
  target,
4533
4543
  isDev: 'development' === environment.config.mode,
@@ -4547,8 +4557,8 @@ ${section.body}` : section.body).join("\n\n"));
4547
4557
  }
4548
4558
  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.`);
4549
4559
  }
4550
- async function generateRspackConfig({ target, context, environment }) {
4551
- let chainUtils = getChainUtils(target, context.environments[environment]), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
4560
+ async function generateRspackConfig({ target, context, environmentName }) {
4561
+ let chainUtils = getChainUtils(target, context.environments[environmentName], context.environments), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
4552
4562
  ...chainUtils,
4553
4563
  bundler: {
4554
4564
  BannerPlugin,
@@ -4676,10 +4686,10 @@ ${section.body}` : section.body).join("\n\n"));
4676
4686
  let normalizedConfig = await initRsbuildConfig({
4677
4687
  context,
4678
4688
  pluginManager
4679
- }), rspackConfigs = await Promise.all(Object.entries(normalizedConfig.environments).map(([environment, config])=>generateRspackConfig({
4689
+ }), rspackConfigs = await Promise.all(Object.entries(normalizedConfig.environments).map(([environmentName, config])=>generateRspackConfig({
4680
4690
  target: config.output.target,
4681
4691
  context,
4682
- environment
4692
+ environmentName
4683
4693
  })));
4684
4694
  if (isDebug()) {
4685
4695
  let inspect = async ()=>{
@@ -4783,8 +4793,8 @@ ${section.body}` : section.body).join("\n\n"));
4783
4793
  logger.ready(`built in ${time}${suffix}`);
4784
4794
  }
4785
4795
  };
4786
- hasErrors || (isMultiCompiler && stats.children?.length ? stats.children.forEach((c, index)=>{
4787
- printTime(c, index);
4796
+ hasErrors || (isMultiCompiler && stats.children?.length ? stats.children.forEach((item, index)=>{
4797
+ printTime(item, index);
4788
4798
  }) : printTime(stats, 0));
4789
4799
  let { message, level } = formatStats(stats, hasErrors);
4790
4800
  'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
@@ -5507,7 +5517,7 @@ ${section.body}` : section.body).join("\n\n"));
5507
5517
  let trailingSlashBase = addTrailingSlash(base);
5508
5518
  return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
5509
5519
  }, getRoutes = (context)=>{
5510
- let environmentWithHtml = Object.values(context.environments).filter((item)=>Object.keys(item.htmlPaths).length > 0);
5520
+ let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
5511
5521
  if (0 === environmentWithHtml.length) return [];
5512
5522
  let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
5513
5523
  return environmentWithHtml.reduce((prev, environmentContext)=>{
@@ -6254,7 +6264,7 @@ ${section.body}` : section.body).join("\n\n"));
6254
6264
  outputFileSystem.stat(filename, (err, stats)=>{
6255
6265
  err ? reject(err) : resolve(stats);
6256
6266
  });
6257
- }), { environments, publicPathnames } = context, distPaths = Object.values(environments).map((env)=>env.distPath), possibleFilenames = new Set();
6267
+ }), { environmentList, publicPathnames } = context, distPaths = environmentList.map((env)=>env.distPath), possibleFilenames = new Set();
6258
6268
  for (let [index, distPath] of distPaths.entries()){
6259
6269
  let prefix = publicPathnames[index];
6260
6270
  prefix && '/' !== prefix && pathname.startsWith(prefix) && possibleFilenames.add(external_node_path_default().join(distPath, pathname.slice(prefix.length)));
@@ -6579,9 +6589,9 @@ ${section.body}` : section.body).join("\n\n"));
6579
6589
  }
6580
6590
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6581
6591
  var config1, environments;
6582
- let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments: environments1 } = context;
6592
+ let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments: environments1, environmentList } = context;
6583
6593
  applyToCompiler(compiler, (compiler, index)=>{
6584
- let environment = Object.values(environments1).find((env)=>env.index === index);
6594
+ let environment = environmentList[index];
6585
6595
  if (!environment) return;
6586
6596
  let token = environment.webSocketToken;
6587
6597
  token && (applyHMREntry({
@@ -6635,7 +6645,7 @@ ${section.body}` : section.body).join("\n\n"));
6635
6645
  }), callbacks.length = 0);
6636
6646
  });
6637
6647
  });
6638
- let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments = environments1).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6648
+ let writeToDisk = (config1 = config.dev, environments = environments1, 1 === new Set(writeToDiskValues = environmentList.map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6639
6649
  let { writeToDisk } = config1;
6640
6650
  return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6641
6651
  });
@@ -7014,7 +7024,7 @@ ${section.body}` : section.body).join("\n\n"));
7014
7024
  upgrade = (req, socket, head)=>{
7015
7025
  if (!this.wsServer.shouldHandle(req)) return;
7016
7026
  let query = parseQueryString(req);
7017
- Object.values(this.context.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7027
+ this.context.environmentList.map(({ webSocketToken })=>webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7018
7028
  this.wsServer.emit('connection', connection, req);
7019
7029
  }) : socket.destroy();
7020
7030
  };
@@ -7095,7 +7105,7 @@ ${section.body}` : section.body).join("\n\n"));
7095
7105
  });
7096
7106
  }
7097
7107
  getStats(token) {
7098
- let { stats } = this.context.buildState, environment = Object.values(this.context.environments).find(({ webSocketToken })=>webSocketToken === token);
7108
+ let { stats } = this.context.buildState, environment = this.context.environmentList.find(({ webSocketToken })=>webSocketToken === token);
7099
7109
  if (!stats || !environment) return;
7100
7110
  let currentStats = stats;
7101
7111
  if (stats.children) {
@@ -7831,30 +7841,31 @@ ${section.body}` : section.body).join("\n\n"));
7831
7841
  if (!htmlPath) throw Error(`${color.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${color.yellow(entryName)}`);
7832
7842
  let fileName = (0, external_node_path_.join)(distPath, htmlPath);
7833
7843
  return utils.readFileSync(fileName);
7834
- })(entryName, utils)), environmentAPI = Object.fromEntries(Object.entries(context.environments).map(([name, environment])=>[
7835
- name,
7836
- {
7837
- getStats: async ()=>{
7838
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getStats')} when ${color.yellow('runCompile')} is false`);
7839
- return await waitLastCompileDone, lastStats[environment.index];
7840
- },
7841
- context: environment,
7842
- loadBundle: async (entryName)=>{
7843
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('loadBundle')} when ${color.yellow('runCompile')} is false`);
7844
- return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
7845
- readFileSync: buildManager.readFileSync,
7846
- environment
7847
- });
7848
- },
7849
- getTransformedHtml: async (entryName)=>{
7850
- if (!buildManager) throw Error(`${color.dim('[rsbuild:server]')} Can not call ${color.yellow('getTransformedHtml')} when ${color.yellow('runCompile')} is false`);
7851
- return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
7852
- readFileSync: buildManager.readFileSync,
7853
- environment
7854
- });
7855
- }
7844
+ })(entryName, utils)), environmentAPI = {}, getErrorMsg = (method)=>`${color.dim('[rsbuild:server]')} Can not call ${color.yellow(method)} when ${color.yellow('runCompile')} is false`;
7845
+ context.environmentList.forEach((environment, index)=>{
7846
+ environmentAPI[environment.name] = {
7847
+ context: environment,
7848
+ getStats: async ()=>{
7849
+ if (!buildManager) throw Error(getErrorMsg('getStats'));
7850
+ return await waitLastCompileDone, lastStats[index];
7851
+ },
7852
+ loadBundle: async (entryName)=>{
7853
+ if (!buildManager) throw Error(getErrorMsg('loadBundle'));
7854
+ return await waitLastCompileDone, cacheableLoadBundle(lastStats[index], entryName, {
7855
+ readFileSync: buildManager.readFileSync,
7856
+ environment
7857
+ });
7858
+ },
7859
+ getTransformedHtml: async (entryName)=>{
7860
+ if (!buildManager) throw Error(getErrorMsg('getTransformedHtml'));
7861
+ return await waitLastCompileDone, cacheableTransformedHtml(lastStats[index], entryName, {
7862
+ readFileSync: buildManager.readFileSync,
7863
+ environment
7864
+ });
7856
7865
  }
7857
- ])), middlewares = requireCompiledPackage('connect')(), httpServer = middlewareMode ? null : await createHttpServer({
7866
+ };
7867
+ });
7868
+ let middlewares = requireCompiledPackage('connect')(), httpServer = middlewareMode ? null : await createHttpServer({
7858
7869
  serverConfig: config.server,
7859
7870
  middlewares
7860
7871
  }), devServerAPI = {
@@ -8191,7 +8202,7 @@ ${section.body}` : section.body).join("\n\n"));
8191
8202
  ],
8192
8203
  single: 'index' === htmlFallback
8193
8204
  });
8194
- this.middlewares.use((req, res, next)=>{
8205
+ this.middlewares.use(function staticAssetMiddleware(req, res, next) {
8195
8206
  let url = req.url, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
8196
8207
  assetPrefix && url?.startsWith(assetPrefix) ? (req.url = url.slice(assetPrefix.length), assetsMiddleware(req, res, (...args)=>{
8197
8208
  req.url = url, next(...args);
@@ -8207,7 +8218,7 @@ ${section.body}` : section.body).join("\n\n"));
8207
8218
  pwd: context.rootPath,
8208
8219
  output: {
8209
8220
  path: context.distPath,
8210
- assetPrefixes: Object.values(context.environments).map((e)=>getPathnameFromUrl(e.config.output.assetPrefix))
8221
+ assetPrefixes: context.environmentList.map((e)=>getPathnameFromUrl(e.config.output.assetPrefix))
8211
8222
  },
8212
8223
  serverConfig
8213
8224
  }, middlewares);
@@ -8873,7 +8884,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8873
8884
  let postcssrcCache = new Map();
8874
8885
  api.modifyBundlerChain({
8875
8886
  order: 'pre',
8876
- handler: async (chain, { target, isProd, CHAIN_ID, environment })=>{
8887
+ handler: async (chain, { target, isProd, CHAIN_ID, environment, environments })=>{
8877
8888
  let config, isProd1, rule = chain.module.rule(CHAIN_ID.RULE.CSS), inlineRule = chain.module.rule(CHAIN_ID.RULE.CSS_INLINE), { config: config1 } = environment;
8878
8889
  rule.test(CSS_REGEX).type("javascript/auto").dependency({
8879
8890
  not: 'url'
@@ -8892,34 +8903,43 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8892
8903
  rule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
8893
8904
  } else rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(getCssExtractPlugin().loader).options(config1.tools.cssExtract.loaderOptions);
8894
8905
  else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(external_node_path_default().join(LOADER_PATH, 'ignoreCssLoader.mjs'));
8895
- let importLoaders = 0, updateRules = (callback)=>{
8896
- callback(rule, 'normal'), callback(inlineRule, 'inline');
8906
+ let importLoaders = {
8907
+ normal: 0,
8908
+ inline: 0
8909
+ }, updateRules = (callback, options = {})=>{
8910
+ options.skipNormal || callback(rule, 'normal'), callback(inlineRule, 'inline');
8897
8911
  }, cssLoaderPath = getCompiledPath('css-loader');
8898
8912
  if (updateRules((rule)=>{
8899
8913
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
8900
- }), emitCss) {
8901
- if ('rspack' === api.context.bundlerType && !1 !== config1.tools.lightningcssLoader) {
8902
- importLoaders++;
8903
- let { minifyCss } = parseMinifyOptions(config1);
8904
- updateRules((rule, type)=>{
8905
- let inlineStyle = 'inline' === type || config1.output.injectStyles, lightningcssOptions = getLightningCSSLoaderOptions(config1, environment.browserslist, inlineStyle && minifyCss);
8906
- rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
8907
- });
8914
+ }), 'rspack' === api.context.bundlerType && !1 !== config1.tools.lightningcssLoader) {
8915
+ emitCss && importLoaders.normal++, importLoaders.inline++;
8916
+ let { minifyCss } = parseMinifyOptions(config1), { browserslist } = environment;
8917
+ if ('node' === target) {
8918
+ let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
8919
+ webEnvironment?.browserslist && (browserslist = webEnvironment.browserslist);
8908
8920
  }
8909
- let postcssLoaderOptions = await getPostcssLoaderOptions({
8910
- config: config1,
8911
- root: api.context.rootPath,
8912
- postcssrcCache
8921
+ updateRules((rule, type)=>{
8922
+ let inlineStyle = 'inline' === type || config1.output.injectStyles, lightningcssOptions = getLightningCSSLoaderOptions(config1, browserslist, inlineStyle && minifyCss);
8923
+ rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
8924
+ }, {
8925
+ skipNormal: !emitCss
8913
8926
  });
8914
- if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
8915
- importLoaders++;
8916
- let postcssLoaderPath = getCompiledPath('postcss-loader');
8917
- updateRules((rule)=>{
8918
- rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
8919
- });
8920
- }
8921
8927
  }
8922
- let localIdentName = (config = config1, isProd1 = isProd, config.output.cssModules.localIdentName || (isProd1 ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]')), cssLoaderOptions = (({ config, importLoaders, localIdentName, emitCss })=>{
8928
+ let postcssLoaderOptions = await getPostcssLoaderOptions({
8929
+ config: config1,
8930
+ root: api.context.rootPath,
8931
+ postcssrcCache
8932
+ });
8933
+ if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
8934
+ emitCss && importLoaders.normal++, importLoaders.inline++;
8935
+ let postcssLoaderPath = getCompiledPath('postcss-loader');
8936
+ updateRules((rule)=>{
8937
+ rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
8938
+ }, {
8939
+ skipNormal: !emitCss
8940
+ });
8941
+ }
8942
+ let localIdentName = (config = config1, isProd1 = isProd, config.output.cssModules.localIdentName || (isProd1 ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]')), cssLoaderOptions = (({ config, localIdentName, emitCss })=>{
8923
8943
  let { cssModules } = config.output;
8924
8944
  return ((options, exportOnlyLocals)=>{
8925
8945
  if (options.modules && exportOnlyLocals) {
@@ -8940,7 +8960,6 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8940
8960
  return options;
8941
8961
  })(reduceConfigs({
8942
8962
  initial: {
8943
- importLoaders,
8944
8963
  modules: {
8945
8964
  ...cssModules,
8946
8965
  localIdentName
@@ -8952,16 +8971,20 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
8952
8971
  }), !emitCss);
8953
8972
  })({
8954
8973
  config: config1,
8955
- importLoaders,
8956
8974
  localIdentName,
8957
8975
  emitCss
8958
8976
  });
8959
8977
  updateRules((rule, type)=>{
8960
- rule.use(CHAIN_ID.USE.CSS).options('inline' === type ? {
8978
+ let finalOptions = cssLoaderOptions;
8979
+ finalOptions = 'inline' === type ? {
8961
8980
  ...cssLoaderOptions,
8962
8981
  exportType: 'string',
8963
- modules: !1
8964
- } : cssLoaderOptions), rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8982
+ modules: !1,
8983
+ importLoaders: importLoaders.inline
8984
+ } : {
8985
+ ...cssLoaderOptions,
8986
+ importLoaders: importLoaders.normal
8987
+ }, rule.use(CHAIN_ID.USE.CSS).options(finalOptions), rule.sideEffects(!0), rule.resolve.preferRelative(!0);
8965
8988
  });
8966
8989
  let isStringExport = 'string' === cssLoaderOptions.exportType;
8967
8990
  if (isStringExport && rule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && rule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), emitCss && !config1.output.injectStyles && !isStringExport) {
@@ -9519,10 +9542,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9519
9542
  name: 'rsbuild:nonce',
9520
9543
  setup (api) {
9521
9544
  api.onAfterCreateCompiler(({ compiler, environments })=>{
9522
- let environmentList = Object.values(environments), nonces = environmentList.map((environment)=>{
9523
- let { nonce } = environment.config.security;
9524
- return nonce;
9525
- });
9545
+ let environmentList = Object.values(environments), nonces = Object.values(environments).map((environment)=>environment.config.security.nonce);
9526
9546
  nonces.some((nonce)=>!!nonce) && applyToCompiler(compiler, (compiler, index)=>{
9527
9547
  let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
9528
9548
  if (!Object.keys(environment?.htmlPaths ?? {}).length || !nonce) return;
@@ -9848,7 +9868,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9848
9868
  };
9849
9869
  function setupCommands() {
9850
9870
  let cli = ((name = "")=>new CAC(name))('rsbuild');
9851
- 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)', {
9871
+ 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)', {
9852
9872
  default: 'auto'
9853
9873
  }).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', {
9854
9874
  type: [
@@ -9917,7 +9937,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9917
9937
  }
9918
9938
  function showGreeting() {
9919
9939
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9920
- logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.6.3\n`);
9940
+ logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.6.4\n`);
9921
9941
  }
9922
9942
  function setupLogLevel() {
9923
9943
  let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
@@ -9938,7 +9958,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
9938
9958
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
9939
9959
  }
9940
9960
  }
9941
- let src_version = "1.6.3";
9961
+ let src_version = "1.6.4";
9942
9962
  })(), 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 === [
9943
9963
  "PLUGIN_CSS_NAME",
9944
9964
  "PLUGIN_SWC_NAME",