@rslib/core 0.0.8 → 0.0.10

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
@@ -6,6 +6,7 @@ import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__ from "../c
6
6
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__ from "../compiled/commander/index.js";
7
7
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
8
8
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__ from "../compiled/fast-glob/index.js";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_node_module__ from "node:module";
9
10
  import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
10
11
  /**
11
12
  * Node.js built-in modules.
@@ -133,7 +134,7 @@ function prepareCli() {
133
134
  // Some package managers automatically output a blank line, some do not.
134
135
  const { npm_execpath } = process.env;
135
136
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
136
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.0.8\n`);
137
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.0.10\n`);
137
138
  }
138
139
  const DEFAULT_CONFIG_NAME = 'rslib.config';
139
140
  const DEFAULT_CONFIG_EXTENSIONS = [
@@ -170,7 +171,124 @@ const ENTRY_EXTENSIONS = [
170
171
  ...CSS_EXTENSIONS
171
172
  ];
172
173
  const JS_EXTENSIONS_PATTERN = new RegExp(`\\.(${JS_EXTENSIONS.join('|')})$`);
174
+ const CSS_EXTENSIONS_PATTERN = new RegExp(`\\.(${CSS_EXTENSIONS.join('|')})$`);
173
175
  const ENTRY_EXTENSIONS_PATTERN = new RegExp(`\\.(${ENTRY_EXTENSIONS.join('|')})$`);
176
+ const pluginName = 'REMOVE_CSS_EXTRACT_ASSET_PLUGIN';
177
+ class RemoveCssExtractAssetPlugin {
178
+ name = pluginName;
179
+ options;
180
+ constructor(options){
181
+ this.options = options;
182
+ }
183
+ apply(compiler) {
184
+ const include = this.options.include;
185
+ compiler.hooks.thisCompilation.tap(pluginName, (compilation)=>{
186
+ compilation.hooks.chunkAsset.tap(pluginName, (_chunk, filename)=>{
187
+ const asset = compilation.getAsset(filename);
188
+ if (!asset) return;
189
+ const needRemove = Boolean(asset.name.match(include));
190
+ if (needRemove) compilation.deleteAsset(filename);
191
+ });
192
+ });
193
+ }
194
+ }
195
+ const cssConfig_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module__.createRequire)(import.meta.url);
196
+ const RSLIB_CSS_ENTRY_FLAG = '__rslib_css__';
197
+ function isCssFile(filepath) {
198
+ return CSS_EXTENSIONS_PATTERN.test(filepath);
199
+ }
200
+ const CSS_MODULE_REG = /\.module\.\w+$/i;
201
+ /**
202
+ * This function is modified based on
203
+ * https://github.com/web-infra-dev/rspack/blob/7b80a45a1c58de7bc506dbb107fad6fda37d2a1f/packages/rspack/src/loader-runner/index.ts#L903
204
+ */ const PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
205
+ function parsePathQueryFragment(str) {
206
+ const match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
207
+ return {
208
+ path: match?.[1]?.replace(/\u200b(.)/g, '$1') || '',
209
+ query: match?.[2] ? match[2].replace(/\u200b(.)/g, '$1') : '',
210
+ fragment: match?.[3] || ''
211
+ };
212
+ }
213
+ function isCssModulesFile(filepath, auto) {
214
+ const filename = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].basename(filepath);
215
+ if (true === auto) return CSS_MODULE_REG.test(filename);
216
+ if (auto instanceof RegExp) return auto.test(filepath);
217
+ if ('function' == typeof auto) {
218
+ const { path, query, fragment } = parsePathQueryFragment(filepath);
219
+ // this is a mock for loader
220
+ return auto(path, query, fragment);
221
+ }
222
+ return false;
223
+ }
224
+ function isCssGlobalFile(filepath, auto) {
225
+ const isCss = isCssFile(filepath);
226
+ if (!isCss) return false;
227
+ const isCssModules = isCssModulesFile(filepath, auto);
228
+ return !isCssModules;
229
+ }
230
+ function cssExternalHandler(request, callback, jsExtension, auto, isStyleRedirect) {
231
+ const isCssModulesRequest = isCssModulesFile(request, auto);
232
+ // cssExtract would execute the file handled by css-loader, so we cannot external the "helper import" from css-loader
233
+ // do not external @rsbuild/core/compiled/css-loader/noSourceMaps.js, sourceMaps.js, api.mjs etc.
234
+ if (/compiled\/css-loader\//.test(request)) return callback();
235
+ // 1. css modules: import './CounterButton.module.scss' -> import './CounterButton.module.mjs'
236
+ // 2. css global: import './CounterButton.scss' -> import './CounterButton.css'
237
+ if ('.' === request[0] && isCssFile(request)) {
238
+ // preserve import './CounterButton.module.scss'
239
+ if (!isStyleRedirect) return callback(null, request);
240
+ if (isCssModulesRequest) return callback(null, request.replace(/\.[^.]+$/, jsExtension));
241
+ return callback(null, request.replace(/\.[^.]+$/, '.css'));
242
+ }
243
+ return false;
244
+ }
245
+ const cssConfig_pluginName = 'rsbuild:lib-css';
246
+ const pluginLibCss = (rootDir)=>({
247
+ name: cssConfig_pluginName,
248
+ setup (api) {
249
+ api.modifyBundlerChain((config, { CHAIN_ID })=>{
250
+ let isUsingCssExtract = false;
251
+ for (const ruleId of [
252
+ CHAIN_ID.RULE.CSS,
253
+ CHAIN_ID.RULE.SASS,
254
+ CHAIN_ID.RULE.LESS,
255
+ CHAIN_ID.RULE.STYLUS
256
+ ]){
257
+ const rule = config.module.rule(ruleId);
258
+ if (rule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT)) {
259
+ isUsingCssExtract = true;
260
+ rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(cssConfig_require.resolve('./libCssExtractLoader.js')).options({
261
+ rootDir
262
+ });
263
+ }
264
+ }
265
+ if (isUsingCssExtract) {
266
+ const cssExtract = CHAIN_ID.PLUGIN.MINI_CSS_EXTRACT;
267
+ config.plugins.delete(cssExtract);
268
+ config.plugin(RemoveCssExtractAssetPlugin.name).use(RemoveCssExtractAssetPlugin, [
269
+ {
270
+ include: new RegExp(`^${RSLIB_CSS_ENTRY_FLAG}`)
271
+ }
272
+ ]);
273
+ }
274
+ });
275
+ }
276
+ });
277
+ const composeCssConfig = (rootDir, bundle = true)=>{
278
+ if (bundle || null === rootDir) return {};
279
+ return {
280
+ plugins: [
281
+ pluginLibCss(rootDir)
282
+ ],
283
+ tools: {
284
+ cssLoader: {
285
+ // Otherwise, external variables will be executed by css-extract and cause an error.
286
+ // e.g: `@import url('./a.css');`
287
+ import: false
288
+ }
289
+ }
290
+ };
291
+ };
174
292
  const importMetaUrlShim = `var __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
175
293
  return typeof document === 'undefined'
176
294
  ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
@@ -561,10 +679,31 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
561
679
  // filename must end with part of pattern that comes after last wildcard
562
680
  let lastWildcardIndex = pattern.length;
563
681
  let hasWildcard = false;
564
- for(let i = pattern.length - 1; i > -1; i--)if ('*' === pattern[i] || '?' === pattern[i]) {
565
- lastWildcardIndex = i;
682
+ let hasExtension = false;
683
+ let hasSlash = false;
684
+ let lastSlashIndex = -1;
685
+ for(let i = pattern.length - 1; i > -1; i--){
686
+ const c = pattern[i];
687
+ if (!hasWildcard) {
688
+ if ('*' === c || '?' === c) {
689
+ lastWildcardIndex = i;
690
+ hasWildcard = true;
691
+ }
692
+ }
693
+ if (!hasSlash) {
694
+ if ('.' === c) hasExtension = true;
695
+ else if ('/' === c) {
696
+ lastSlashIndex = i;
697
+ hasSlash = true;
698
+ }
699
+ }
700
+ if (hasWildcard && hasSlash) break;
701
+ }
702
+ if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
703
+ // add implicit glob
704
+ pattern += `${pattern.endsWith('/') ? '' : '/'}${GLOB_ALL_PATTERN}`;
705
+ lastWildcardIndex = pattern.length - 1;
566
706
  hasWildcard = true;
567
- break;
568
707
  }
569
708
  // if pattern does not end with wildcard, filename must end with pattern after last wildcard
570
709
  if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
@@ -581,8 +720,10 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
581
720
  break;
582
721
  }
583
722
  if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
584
- // if no wildcard in pattern, filename must be equal to resolved pattern
585
- if (!hasWildcard) return filename === resolvedPattern;
723
+ if (!hasWildcard) // no wildcard in pattern, filename must be equal to resolved pattern
724
+ return filename === resolvedPattern;
725
+ if (firstWildcardIndex + GLOB_ALL_PATTERN.length === resolvedPattern.length - (pattern.length - 1 - lastWildcardIndex) && resolvedPattern.slice(firstWildcardIndex, firstWildcardIndex + GLOB_ALL_PATTERN.length) === GLOB_ALL_PATTERN) // singular glob-all pattern and we already validated prefix and suffix matches
726
+ return true;
586
727
  // complex pattern, use regex to check it
587
728
  if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
588
729
  const regex = pattern2regex(resolvedPattern, allowJs);
@@ -1231,20 +1372,22 @@ const composeAutoExternalConfig = (options)=>{
1231
1372
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.warn('autoExternal configuration will not be applied due to read package.json failed');
1232
1373
  return {};
1233
1374
  }
1375
+ // User externals configuration has higher priority than autoExternal
1376
+ // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
1377
+ // Only handle the case where the externals type is object, string / string[] does not need to be processed, other types are too complex.
1378
+ const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
1234
1379
  const externalOptions = {
1235
1380
  dependencies: true,
1381
+ optionalDependencies: true,
1236
1382
  peerDependencies: true,
1237
1383
  devDependencies: false,
1238
1384
  ...true === autoExternal ? {} : autoExternal
1239
1385
  };
1240
- // User externals configuration has higher priority than autoExternal
1241
- // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
1242
- // Only handle the case where the externals type is object, string / string[] does not need to be processed, other types are too complex.
1243
- const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
1244
1386
  const externals = [
1245
1387
  'dependencies',
1246
1388
  'peerDependencies',
1247
- 'devDependencies'
1389
+ 'devDependencies',
1390
+ 'optionalDependencies'
1248
1391
  ].reduce((prev, type)=>{
1249
1392
  if (externalOptions[type]) return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
1250
1393
  return prev;
@@ -1403,27 +1546,36 @@ async function createConstantRsbuildConfig() {
1403
1546
  });
1404
1547
  }
1405
1548
  const composeFormatConfig = (format)=>{
1549
+ const jsParserOptions = {
1550
+ importMeta: false,
1551
+ requireResolve: false,
1552
+ requireDynamic: false,
1553
+ requireAsExpression: false,
1554
+ importDynamic: false
1555
+ };
1406
1556
  switch(format){
1407
1557
  case 'esm':
1408
1558
  return {
1409
1559
  tools: {
1410
1560
  rspack: {
1411
- output: {
1412
- module: true,
1413
- chunkFormat: 'module',
1414
- library: {
1415
- type: 'modern-module'
1416
- }
1417
- },
1418
1561
  module: {
1419
1562
  parser: {
1420
- javascript: {
1421
- importMeta: false
1422
- }
1563
+ javascript: jsParserOptions
1423
1564
  }
1424
1565
  },
1425
1566
  optimization: {
1426
- concatenateModules: true
1567
+ concatenateModules: true,
1568
+ sideEffects: 'flag'
1569
+ },
1570
+ output: {
1571
+ module: true,
1572
+ chunkFormat: 'module',
1573
+ library: {
1574
+ type: 'modern-module'
1575
+ },
1576
+ chunkLoading: 'import',
1577
+ workerChunkLoading: 'import',
1578
+ wasmLoading: 'fetch'
1427
1579
  },
1428
1580
  experiments: {
1429
1581
  outputModule: true
@@ -1440,9 +1592,7 @@ const composeFormatConfig = (format)=>{
1440
1592
  rspack: {
1441
1593
  module: {
1442
1594
  parser: {
1443
- javascript: {
1444
- importMeta: false
1445
- }
1595
+ javascript: jsParserOptions
1446
1596
  }
1447
1597
  },
1448
1598
  output: {
@@ -1450,7 +1600,10 @@ const composeFormatConfig = (format)=>{
1450
1600
  chunkFormat: 'commonjs',
1451
1601
  library: {
1452
1602
  type: 'commonjs'
1453
- }
1603
+ },
1604
+ chunkLoading: 'require',
1605
+ workerChunkLoading: 'async-node',
1606
+ wasmLoading: 'async-node'
1454
1607
  }
1455
1608
  }
1456
1609
  }
@@ -1552,12 +1705,18 @@ const composeSyntaxConfig = (syntax, target)=>{
1552
1705
  }
1553
1706
  };
1554
1707
  };
1555
- const composeEntryConfig = async (entries, bundle, root)=>{
1556
- if (!entries) return {};
1708
+ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
1709
+ if (!entries) return {
1710
+ entryConfig: {},
1711
+ lcp: null
1712
+ };
1557
1713
  if (false !== bundle) return {
1558
- source: {
1559
- entry: entries
1560
- }
1714
+ entryConfig: {
1715
+ source: {
1716
+ entry: entries
1717
+ }
1718
+ },
1719
+ lcp: null
1561
1720
  };
1562
1721
  // In bundleless mode, resolve glob patterns and convert them to entry object.
1563
1722
  const resolvedEntries = {};
@@ -1582,21 +1741,35 @@ const composeEntryConfig = async (entries, bundle, root)=>{
1582
1741
  const lcp = await calcLongestCommonPath(resolvedEntryFiles);
1583
1742
  // Using the longest common path of all non-declaration input files by default.
1584
1743
  const outBase = null === lcp ? root : lcp;
1585
- for (const file of resolvedEntryFiles){
1744
+ function getEntryName(file) {
1586
1745
  const { dir, name } = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].parse(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(outBase, file));
1587
1746
  // Entry filename contains nested path to preserve source directory structure.
1588
1747
  const entryFileName = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(dir, name);
1589
- resolvedEntries[entryFileName] = file;
1748
+ // 1. we mark the global css files (which will generate empty js chunk in cssExtract), and deleteAsset in RemoveCssExtractAssetPlugin
1749
+ // 2. avoid the same name e.g: `index.ts` and `index.css`
1750
+ if (isCssGlobalFile(file, cssModulesAuto)) return `${RSLIB_CSS_ENTRY_FLAG}/${entryFileName}`;
1751
+ return entryFileName;
1752
+ }
1753
+ for (const file of resolvedEntryFiles){
1754
+ const entryName = getEntryName(file);
1755
+ if (resolvedEntries[entryName]) __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.warn(`duplicate entry: ${entryName}, this may lead to the incorrect output, please rename the file`);
1756
+ resolvedEntries[entryName] = file;
1590
1757
  }
1591
1758
  }
1592
- return {
1759
+ const lcp = await calcLongestCommonPath(Object.values(resolvedEntries));
1760
+ const entryConfig = {
1593
1761
  source: {
1594
1762
  entry: resolvedEntries
1595
1763
  }
1596
1764
  };
1765
+ return {
1766
+ entryConfig,
1767
+ lcp
1768
+ };
1597
1769
  };
1598
- const composeBundleConfig = (jsExtension, bundle = true)=>{
1770
+ const composeBundleConfig = (jsExtension, redirect, cssModulesAuto, bundle = true)=>{
1599
1771
  if (bundle) return {};
1772
+ const isStyleRedirect = redirect.style ?? true;
1600
1773
  return {
1601
1774
  output: {
1602
1775
  externals: [
@@ -1611,8 +1784,11 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1611
1784
  // This may result in a change in semantics,
1612
1785
  // user should use copy to keep origin file or use another separate entry to deal this
1613
1786
  let request = data.request;
1787
+ const cssExternal = cssExternalHandler(request, callback, jsExtension, cssModulesAuto, isStyleRedirect);
1788
+ if (false !== cssExternal) return cssExternal;
1614
1789
  if ('.' === request[0]) {
1615
- if ((0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(request)) {
1790
+ const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(request);
1791
+ if (ext) {
1616
1792
  if (!JS_EXTENSIONS_PATTERN.test(request)) // If it does not match jsExtensionsPattern, we should do nothing, eg: ./foo.png
1617
1793
  return callback();
1618
1794
  request = request.replace(/\.[^.]+$/, jsExtension);
@@ -1636,7 +1812,7 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1636
1812
  bundle: dts?.bundle ?? bundle,
1637
1813
  distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
1638
1814
  abortOnError: dts?.abortOnError ?? true,
1639
- dtsExtension,
1815
+ dtsExtension: dts?.autoExtension ? dtsExtension : '.d.ts',
1640
1816
  autoExternal,
1641
1817
  banner: banner?.dts,
1642
1818
  footer: footer?.dts
@@ -1652,12 +1828,7 @@ const composeTargetConfig = (target = 'web')=>{
1652
1828
  rspack: {
1653
1829
  target: [
1654
1830
  'web'
1655
- ],
1656
- output: {
1657
- chunkLoading: 'import',
1658
- workerChunkLoading: 'import',
1659
- wasmLoading: 'fetch'
1660
- }
1831
+ ]
1661
1832
  }
1662
1833
  }
1663
1834
  };
@@ -1667,15 +1838,7 @@ const composeTargetConfig = (target = 'web')=>{
1667
1838
  rspack: {
1668
1839
  target: [
1669
1840
  'node'
1670
- ],
1671
- // "__dirname" and "__filename" shims will automatically be enabled when `output.module` is `true`,
1672
- // and leave them as-is in the rest of the cases.
1673
- // { node: { __dirname: ..., __filename: ... } }
1674
- output: {
1675
- chunkLoading: 'require',
1676
- workerChunkLoading: 'async-node',
1677
- wasmLoading: 'async-node'
1678
- }
1841
+ ]
1679
1842
  }
1680
1843
  },
1681
1844
  output: {
@@ -1731,12 +1894,13 @@ async function composeLibRsbuildConfig(config, configPath) {
1731
1894
  const rootPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath);
1732
1895
  const pkgJson = readPackageJson(rootPath);
1733
1896
  const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
1734
- const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false } = config;
1897
+ const cssModulesAuto = config.output?.cssModules?.auto ?? true;
1898
+ const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false, redirect = {} } = config;
1735
1899
  const formatConfig = composeFormatConfig(format);
1736
1900
  const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
1737
1901
  const externalsConfig = composeExternalsConfig(format, config.output?.externals);
1738
1902
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
1739
- const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
1903
+ const bundleConfig = composeBundleConfig(jsExtension, redirect, cssModulesAuto, config.bundle);
1740
1904
  const targetConfig = composeTargetConfig(config.output?.target);
1741
1905
  const syntaxConfig = composeSyntaxConfig(config?.syntax, config.output?.target);
1742
1906
  const autoExternalConfig = composeAutoExternalConfig({
@@ -1744,13 +1908,14 @@ async function composeLibRsbuildConfig(config, configPath) {
1744
1908
  pkgJson,
1745
1909
  userExternals: config.output?.externals
1746
1910
  });
1747
- const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath));
1911
+ const { entryConfig, lcp } = await composeEntryConfig(config.source?.entry, config.bundle, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath), cssModulesAuto);
1912
+ const cssConfig = composeCssConfig(lcp, config.bundle);
1748
1913
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
1749
1914
  const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1750
1915
  const minifyConfig = composeMinifyConfig(config.output?.minify);
1751
1916
  const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
1752
1917
  const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
1753
- return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1918
+ return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, cssConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1754
1919
  }
1755
1920
  async function composeCreateRsbuildConfig(rslibConfig, path) {
1756
1921
  const constantRsbuildConfig = await createConstantRsbuildConfig();
@@ -1785,6 +1950,7 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
1785
1950
  'format',
1786
1951
  'autoExtension',
1787
1952
  'autoExternal',
1953
+ 'redirect',
1788
1954
  'syntax',
1789
1955
  'externalHelpers',
1790
1956
  'banner',
@@ -1830,7 +1996,7 @@ const applyCommonOptions = (command)=>{
1830
1996
  command.option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file');
1831
1997
  };
1832
1998
  function runCli() {
1833
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.0.8");
1999
+ __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.0.10");
1834
2000
  const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('build');
1835
2001
  const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('inspect');
1836
2002
  [
@@ -1872,6 +2038,6 @@ function runCli() {
1872
2038
  });
1873
2039
  __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.parse();
1874
2040
  }
1875
- const src_version = "0.0.8";
2041
+ const src_version = "0.0.10";
1876
2042
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger;
1877
2043
  export { build, defineConfig, loadConfig, prepareCli, runCli, src_version as version, __webpack_exports__logger as logger };
@@ -0,0 +1,125 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
2
+ /**
3
+ * The following code is modified based on
4
+ * https://github.com/web-infra-dev/rspack/blob/0a89e433a9f8596a7c6c4326542f168b5982d2da/packages/rspack/src/builtin-plugin/css-extract/loader.ts
5
+ * 1. remove hmr/webpack runtime
6
+ * 2. add `this.emitFile` to emit css files
7
+ * 3. add `import './[name].css';`
8
+ */ const PLUGIN_NAME = 'LIB_CSS_EXTRACT_LOADER';
9
+ function stringifyLocal(value) {
10
+ return 'function' == typeof value ? value.toString() : JSON.stringify(value);
11
+ }
12
+ const libCssExtractLoader_loader = function(content) {
13
+ if (this._compiler?.options?.experiments?.css && this._module && ('css' === this._module.type || 'css/auto' === this._module.type || 'css/global' === this._module.type || 'css/module' === this._module.type)) return content;
14
+ };
15
+ const pitch = function(request, _, _data) {
16
+ if (this._compiler?.options?.experiments?.css && this._module && ('css' === this._module.type || 'css/auto' === this._module.type || 'css/global' === this._module.type || 'css/module' === this._module.type)) {
17
+ const e = new Error("use type 'css' and `CssExtractRspackPlugin` together, please set `experiments.css` to `false` or set `{ type: \"javascript/auto\" }` for rules with `CssExtractRspackPlugin` in your rspack config (now `CssExtractRspackPlugin` does nothing).");
18
+ e.stack = void 0;
19
+ this.emitWarning(e);
20
+ return;
21
+ }
22
+ const options = this.getOptions();
23
+ const emit = void 0 === options.emit || options.emit;
24
+ const callback = this.async();
25
+ const filepath = this.resourcePath;
26
+ const rootDir = options.rootDir ?? this.rootContext;
27
+ const handleExports = (originalExports)=>{
28
+ let locals;
29
+ let namedExport;
30
+ const esModule = void 0 === options.esModule || options.esModule;
31
+ let dependencies = [];
32
+ try {
33
+ // eslint-disable-next-line no-underscore-dangle
34
+ const exports = originalExports.__esModule ? originalExports.default : originalExports;
35
+ namedExport = originalExports.__esModule && (!originalExports.default || !('locals' in originalExports.default));
36
+ if (namedExport) {
37
+ for (const key of Object.keys(originalExports))if ('default' !== key) {
38
+ if (!locals) locals = {};
39
+ locals[key] = originalExports[key];
40
+ }
41
+ } else locals = exports?.locals;
42
+ if (Array.isArray(exports) && emit) {
43
+ const identifierCountMap = new Map();
44
+ dependencies = exports.map(([id, content, media, sourceMap, supports, layer])=>{
45
+ const identifier = id;
46
+ const context = this.rootContext;
47
+ const count = identifierCountMap.get(identifier) || 0;
48
+ identifierCountMap.set(identifier, count + 1);
49
+ return {
50
+ identifier,
51
+ context,
52
+ content,
53
+ media,
54
+ supports,
55
+ layer,
56
+ identifierIndex: count,
57
+ sourceMap: sourceMap ? JSON.stringify(sourceMap) : void 0,
58
+ filepath
59
+ };
60
+ }).filter((item)=>null !== item);
61
+ }
62
+ } catch (e) {
63
+ callback(e);
64
+ return;
65
+ }
66
+ const result = function() {
67
+ if (locals) {
68
+ if (namedExport) {
69
+ const identifiers = Array.from(function*() {
70
+ let identifierId = 0;
71
+ for (const key of Object.keys(locals)){
72
+ identifierId += 1;
73
+ yield [
74
+ `_${identifierId.toString(16)}`,
75
+ key
76
+ ];
77
+ }
78
+ }());
79
+ const localsString = identifiers.map(([id, key])=>`\nvar ${id} = ${stringifyLocal(locals[key])};`).join('');
80
+ const exportsString = `export { ${identifiers.map(([id, key])=>`${id} as ${JSON.stringify(key)}`).join(', ')} }`;
81
+ const defaultExport = void 0 !== options.defaultExport && options.defaultExport;
82
+ return defaultExport ? `${localsString}\n${exportsString}\nexport default { ${identifiers.map(([id, key])=>`${JSON.stringify(key)}: ${id}`).join(', ')} }\n` : `${localsString}\n${exportsString}\n`;
83
+ }
84
+ return `\n${esModule ? 'export default' : 'module.exports = '} ${JSON.stringify(locals)};`;
85
+ }
86
+ if (esModule) return '\nexport {};';
87
+ return '';
88
+ }();
89
+ let resultSource = `// extracted by ${PLUGIN_NAME}`;
90
+ let importCssFiles = '';
91
+ function getRelativePath(from, to) {
92
+ let relativePath = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(from, to);
93
+ if (!relativePath.startsWith('./') && !relativePath.startsWith('../') && !__WEBPACK_EXTERNAL_MODULE_node_path__["default"].isAbsolute(relativePath)) relativePath = `./${relativePath}`;
94
+ return relativePath;
95
+ }
96
+ const m = new Map();
97
+ for (const { content, filepath } of dependencies){
98
+ let distFilepath = getRelativePath(rootDir, filepath);
99
+ const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(distFilepath);
100
+ if ('css' !== ext) distFilepath = distFilepath.replace(ext, '.css');
101
+ distFilepath = distFilepath.replace(/\.module\.css/, '_module.css');
102
+ const cssFilename = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].basename(distFilepath);
103
+ if (content.trim()) {
104
+ m.get(distFilepath) ? m.set(distFilepath, `${m.get(distFilepath) + content}\n`) : m.set(distFilepath, `${content}\n`);
105
+ importCssFiles += '\n';
106
+ importCssFiles += `import "./${cssFilename}"`;
107
+ }
108
+ }
109
+ for (const [distFilepath, content] of m.entries())this.emitFile(distFilepath, content);
110
+ resultSource += importCssFiles;
111
+ resultSource += result;
112
+ callback(null, resultSource, void 0);
113
+ };
114
+ this.importModule(`${this.resourcePath}.webpack[javascript/auto]!=!!!${request}`, {
115
+ layer: options.layer
116
+ }, (error, exports)=>{
117
+ if (error) {
118
+ callback(error);
119
+ return;
120
+ }
121
+ handleExports(exports);
122
+ });
123
+ };
124
+ /* harmony default export */ const libCssExtractLoader = libCssExtractLoader_loader;
125
+ export { libCssExtractLoader as default, pitch };
@@ -5,4 +5,5 @@ export declare const JS_EXTENSIONS: string[];
5
5
  export declare const CSS_EXTENSIONS: string[];
6
6
  export declare const ENTRY_EXTENSIONS: string[];
7
7
  export declare const JS_EXTENSIONS_PATTERN: RegExp;
8
+ export declare const CSS_EXTENSIONS_PATTERN: RegExp;
8
9
  export declare const ENTRY_EXTENSIONS_PATTERN: RegExp;
@@ -0,0 +1,11 @@
1
+ import type { Compiler, RspackPluginInstance } from '@rspack/core';
2
+ type Options = {
3
+ include: RegExp;
4
+ };
5
+ declare class RemoveCssExtractAssetPlugin implements RspackPluginInstance {
6
+ readonly name: string;
7
+ options: Options;
8
+ constructor(options: Options);
9
+ apply(compiler: Compiler): void;
10
+ }
11
+ export { RemoveCssExtractAssetPlugin };
@@ -0,0 +1,17 @@
1
+ import type { CSSLoaderOptions, RsbuildConfig } from '@rsbuild/core';
2
+ export declare const RSLIB_CSS_ENTRY_FLAG = "__rslib_css__";
3
+ export type CssLoaderOptionsAuto = CSSLoaderOptions['modules'] extends infer T ? T extends {
4
+ auto?: any;
5
+ } ? T['auto'] : never : never;
6
+ export declare function isCssFile(filepath: string): boolean;
7
+ export declare function parsePathQueryFragment(str: string): {
8
+ path: string;
9
+ query: string;
10
+ fragment: string;
11
+ };
12
+ export declare function isCssModulesFile(filepath: string, auto: CssLoaderOptionsAuto): boolean;
13
+ export declare function isCssGlobalFile(filepath: string, auto: CssLoaderOptionsAuto): boolean;
14
+ type ExternalCallback = (arg0?: null, arg1?: string) => void;
15
+ export declare function cssExternalHandler(request: string, callback: ExternalCallback, jsExtension: string, auto: CssLoaderOptionsAuto, isStyleRedirect: boolean): void | false;
16
+ export declare const composeCssConfig: (rootDir: string | null, bundle?: boolean) => RsbuildConfig;
17
+ export {};
@@ -0,0 +1,11 @@
1
+ import type { LoaderDefinition } from '@rspack/core';
2
+ export interface CssExtractRspackLoaderOptions {
3
+ emit?: boolean;
4
+ esModule?: boolean;
5
+ layer?: string;
6
+ defaultExport?: boolean;
7
+ rootDir?: string;
8
+ }
9
+ declare const loader: LoaderDefinition;
10
+ export declare const pitch: LoaderDefinition['pitch'];
11
+ export default loader;
@@ -1,15 +1,14 @@
1
1
  import type { RsbuildConfig } from '@rsbuild/core';
2
+ import type { PluginDtsOptions } from 'rsbuild-plugin-dts';
2
3
  export type Format = 'esm' | 'cjs' | 'umd';
3
4
  export type FixedEcmaVersions = 'es5' | 'es6' | 'es2015' | 'es2016' | 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'es2023';
4
5
  export type LatestEcmaVersions = 'es2024' | 'esnext';
5
6
  export type EcmaScriptVersion = FixedEcmaVersions | LatestEcmaVersions;
6
7
  export type RsbuildConfigOutputTarget = NonNullable<RsbuildConfig['output']>['target'];
7
8
  export type Syntax = EcmaScriptVersion | string[];
8
- export type Dts = {
9
- bundle: boolean;
10
- distPath?: string;
11
- abortOnError?: boolean;
12
- } | false;
9
+ export type Dts = (Pick<PluginDtsOptions, 'bundle' | 'distPath' | 'abortOnError'> & {
10
+ autoExtension?: boolean;
11
+ }) | false;
13
12
  export type AutoExternal = boolean | {
14
13
  dependencies?: boolean;
15
14
  devDependencies?: boolean;
@@ -20,11 +19,15 @@ export type BannerAndFooter = {
20
19
  css?: string;
21
20
  dts?: string;
22
21
  };
22
+ export type Redirect = {
23
+ style?: boolean;
24
+ };
23
25
  export interface LibConfig extends RsbuildConfig {
24
26
  bundle?: boolean;
25
27
  format?: Format;
26
28
  autoExtension?: boolean;
27
29
  autoExternal?: AutoExternal;
30
+ redirect?: Redirect;
28
31
  /** Support esX and browserslist query */
29
32
  syntax?: Syntax;
30
33
  externalHelpers?: boolean;
@@ -1,6 +1,7 @@
1
1
  export type PkgJson = {
2
+ type?: 'module' | 'commonjs';
2
3
  dependencies?: Record<string, string>;
3
4
  peerDependencies?: Record<string, string>;
4
5
  devDependencies?: Record<string, string>;
5
- [key: string]: unknown;
6
+ optionalDependencies?: Record<string, string>;
6
7
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rslib/core",
3
- "version": "0.0.8",
3
+ "version": "0.0.10",
4
4
  "description": "The Rspack-based library build tool.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -32,21 +32,22 @@
32
32
  "compiled"
33
33
  ],
34
34
  "dependencies": {
35
- "@rsbuild/core": "1.0.7",
36
- "rsbuild-plugin-dts": "0.0.8"
35
+ "@rsbuild/core": "1.0.12",
36
+ "rsbuild-plugin-dts": "0.0.10"
37
37
  },
38
38
  "devDependencies": {
39
+ "@rspack/core": "1.0.8",
39
40
  "@types/fs-extra": "^11.0.4",
40
41
  "commander": "^12.1.0",
41
42
  "fast-glob": "^3.3.2",
42
43
  "fs-extra": "^11.2.0",
43
- "memfs": "^4.12.0",
44
+ "memfs": "^4.13.0",
44
45
  "picocolors": "1.1.0",
45
46
  "prebundle": "1.2.2",
46
- "rslib": "npm:@rslib/core@0.0.7",
47
+ "rslib": "npm:@rslib/core@0.0.9",
47
48
  "rslog": "^1.2.3",
48
- "tsconfck": "3.1.3",
49
- "typescript": "^5.6.2",
49
+ "tsconfck": "3.1.4",
50
+ "typescript": "^5.6.3",
50
51
  "@rslib/tsconfig": "0.0.1"
51
52
  },
52
53
  "peerDependencies": {