@rslib/core 0.0.9 → 0.0.11

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.9\n`);
137
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.0.11\n`);
137
138
  }
138
139
  const DEFAULT_CONFIG_NAME = 'rslib.config';
139
140
  const DEFAULT_CONFIG_EXTENSIONS = [
@@ -170,14 +171,130 @@ 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('|')})$`);
174
- const importMetaUrlShim = `var __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
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
+ };
292
+ const importMetaUrlShim = `/*#__PURE__*/ (function () {
175
293
  return typeof document === 'undefined'
176
294
  ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
177
295
  : (document.currentScript && document.currentScript.src) ||
178
296
  new URL('main.js', document.baseURI).href;
179
- })();
180
- `;
297
+ })()`;
181
298
  // This Rsbuild plugin will shim `import.meta.url` for CommonJS modules.
182
299
  // - Replace `import.meta.url` with `importMetaUrl`.
183
300
  // - Inject `importMetaUrl` to the end of the module (can't inject at the beginning because of `"use strict";`).
@@ -188,20 +305,9 @@ const pluginCjsShim = ()=>({
188
305
  api.modifyEnvironmentConfig((config)=>{
189
306
  config.source.define = {
190
307
  ...config.source.define,
191
- 'import.meta.url': '__rslib_import_meta_url__'
308
+ 'import.meta.url': importMetaUrlShim
192
309
  };
193
310
  });
194
- api.modifyRspackConfig((config)=>{
195
- config.plugins ??= [];
196
- config.plugins.push(new __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.BannerPlugin({
197
- banner: importMetaUrlShim,
198
- // Just before minify stage, to perform tree shaking.
199
- stage: __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE - 1,
200
- raw: true,
201
- footer: true,
202
- include: /\.(js|cjs)$/
203
- }));
204
- });
205
311
  }
206
312
  });
207
313
  const getDefaultExtension = (options)=>{
@@ -561,10 +667,31 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
561
667
  // filename must end with part of pattern that comes after last wildcard
562
668
  let lastWildcardIndex = pattern.length;
563
669
  let hasWildcard = false;
564
- for(let i = pattern.length - 1; i > -1; i--)if ('*' === pattern[i] || '?' === pattern[i]) {
565
- lastWildcardIndex = i;
670
+ let hasExtension = false;
671
+ let hasSlash = false;
672
+ let lastSlashIndex = -1;
673
+ for(let i = pattern.length - 1; i > -1; i--){
674
+ const c = pattern[i];
675
+ if (!hasWildcard) {
676
+ if ('*' === c || '?' === c) {
677
+ lastWildcardIndex = i;
678
+ hasWildcard = true;
679
+ }
680
+ }
681
+ if (!hasSlash) {
682
+ if ('.' === c) hasExtension = true;
683
+ else if ('/' === c) {
684
+ lastSlashIndex = i;
685
+ hasSlash = true;
686
+ }
687
+ }
688
+ if (hasWildcard && hasSlash) break;
689
+ }
690
+ if (!hasExtension && (!hasWildcard || lastWildcardIndex < lastSlashIndex)) {
691
+ // add implicit glob
692
+ pattern += `${pattern.endsWith('/') ? '' : '/'}${GLOB_ALL_PATTERN}`;
693
+ lastWildcardIndex = pattern.length - 1;
566
694
  hasWildcard = true;
567
- break;
568
695
  }
569
696
  // if pattern does not end with wildcard, filename must end with pattern after last wildcard
570
697
  if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
@@ -581,8 +708,10 @@ const IS_POSIX = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.sep ===
581
708
  break;
582
709
  }
583
710
  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;
711
+ if (!hasWildcard) // no wildcard in pattern, filename must be equal to resolved pattern
712
+ return filename === resolvedPattern;
713
+ 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
714
+ return true;
586
715
  // complex pattern, use regex to check it
587
716
  if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
588
717
  const regex = pattern2regex(resolvedPattern, allowJs);
@@ -1231,20 +1360,22 @@ const composeAutoExternalConfig = (options)=>{
1231
1360
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.warn('autoExternal configuration will not be applied due to read package.json failed');
1232
1361
  return {};
1233
1362
  }
1363
+ // User externals configuration has higher priority than autoExternal
1364
+ // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
1365
+ // Only handle the case where the externals type is object, string / string[] does not need to be processed, other types are too complex.
1366
+ const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
1234
1367
  const externalOptions = {
1235
1368
  dependencies: true,
1369
+ optionalDependencies: true,
1236
1370
  peerDependencies: true,
1237
1371
  devDependencies: false,
1238
1372
  ...true === autoExternal ? {} : autoExternal
1239
1373
  };
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
1374
  const externals = [
1245
1375
  'dependencies',
1246
1376
  'peerDependencies',
1247
- 'devDependencies'
1377
+ 'devDependencies',
1378
+ 'optionalDependencies'
1248
1379
  ].reduce((prev, type)=>{
1249
1380
  if (externalOptions[type]) return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
1250
1381
  return prev;
@@ -1562,12 +1693,18 @@ const composeSyntaxConfig = (syntax, target)=>{
1562
1693
  }
1563
1694
  };
1564
1695
  };
1565
- const composeEntryConfig = async (entries, bundle, root)=>{
1566
- if (!entries) return {};
1696
+ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
1697
+ if (!entries) return {
1698
+ entryConfig: {},
1699
+ lcp: null
1700
+ };
1567
1701
  if (false !== bundle) return {
1568
- source: {
1569
- entry: entries
1570
- }
1702
+ entryConfig: {
1703
+ source: {
1704
+ entry: entries
1705
+ }
1706
+ },
1707
+ lcp: null
1571
1708
  };
1572
1709
  // In bundleless mode, resolve glob patterns and convert them to entry object.
1573
1710
  const resolvedEntries = {};
@@ -1592,21 +1729,35 @@ const composeEntryConfig = async (entries, bundle, root)=>{
1592
1729
  const lcp = await calcLongestCommonPath(resolvedEntryFiles);
1593
1730
  // Using the longest common path of all non-declaration input files by default.
1594
1731
  const outBase = null === lcp ? root : lcp;
1595
- for (const file of resolvedEntryFiles){
1732
+ function getEntryName(file) {
1596
1733
  const { dir, name } = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].parse(__WEBPACK_EXTERNAL_MODULE_node_path__["default"].relative(outBase, file));
1597
1734
  // Entry filename contains nested path to preserve source directory structure.
1598
1735
  const entryFileName = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(dir, name);
1599
- resolvedEntries[entryFileName] = file;
1736
+ // 1. we mark the global css files (which will generate empty js chunk in cssExtract), and deleteAsset in RemoveCssExtractAssetPlugin
1737
+ // 2. avoid the same name e.g: `index.ts` and `index.css`
1738
+ if (isCssGlobalFile(file, cssModulesAuto)) return `${RSLIB_CSS_ENTRY_FLAG}/${entryFileName}`;
1739
+ return entryFileName;
1740
+ }
1741
+ for (const file of resolvedEntryFiles){
1742
+ const entryName = getEntryName(file);
1743
+ 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`);
1744
+ resolvedEntries[entryName] = file;
1600
1745
  }
1601
1746
  }
1602
- return {
1747
+ const lcp = await calcLongestCommonPath(Object.values(resolvedEntries));
1748
+ const entryConfig = {
1603
1749
  source: {
1604
1750
  entry: resolvedEntries
1605
1751
  }
1606
1752
  };
1753
+ return {
1754
+ entryConfig,
1755
+ lcp
1756
+ };
1607
1757
  };
1608
- const composeBundleConfig = (jsExtension, bundle = true)=>{
1758
+ const composeBundleConfig = (jsExtension, redirect, cssModulesAuto, bundle = true)=>{
1609
1759
  if (bundle) return {};
1760
+ const isStyleRedirect = redirect.style ?? true;
1610
1761
  return {
1611
1762
  output: {
1612
1763
  externals: [
@@ -1621,8 +1772,11 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1621
1772
  // This may result in a change in semantics,
1622
1773
  // user should use copy to keep origin file or use another separate entry to deal this
1623
1774
  let request = data.request;
1775
+ const cssExternal = cssExternalHandler(request, callback, jsExtension, cssModulesAuto, isStyleRedirect);
1776
+ if (false !== cssExternal) return cssExternal;
1624
1777
  if ('.' === request[0]) {
1625
- if ((0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(request)) {
1778
+ const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(request);
1779
+ if (ext) {
1626
1780
  if (!JS_EXTENSIONS_PATTERN.test(request)) // If it does not match jsExtensionsPattern, we should do nothing, eg: ./foo.png
1627
1781
  return callback();
1628
1782
  request = request.replace(/\.[^.]+$/, jsExtension);
@@ -1646,7 +1800,7 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1646
1800
  bundle: dts?.bundle ?? bundle,
1647
1801
  distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
1648
1802
  abortOnError: dts?.abortOnError ?? true,
1649
- dtsExtension,
1803
+ dtsExtension: dts?.autoExtension ? dtsExtension : '.d.ts',
1650
1804
  autoExternal,
1651
1805
  banner: banner?.dts,
1652
1806
  footer: footer?.dts
@@ -1728,12 +1882,13 @@ async function composeLibRsbuildConfig(config, configPath) {
1728
1882
  const rootPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath);
1729
1883
  const pkgJson = readPackageJson(rootPath);
1730
1884
  const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
1731
- const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false } = config;
1885
+ const cssModulesAuto = config.output?.cssModules?.auto ?? true;
1886
+ const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false, redirect = {} } = config;
1732
1887
  const formatConfig = composeFormatConfig(format);
1733
1888
  const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
1734
1889
  const externalsConfig = composeExternalsConfig(format, config.output?.externals);
1735
1890
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
1736
- const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
1891
+ const bundleConfig = composeBundleConfig(jsExtension, redirect, cssModulesAuto, config.bundle);
1737
1892
  const targetConfig = composeTargetConfig(config.output?.target);
1738
1893
  const syntaxConfig = composeSyntaxConfig(config?.syntax, config.output?.target);
1739
1894
  const autoExternalConfig = composeAutoExternalConfig({
@@ -1741,13 +1896,14 @@ async function composeLibRsbuildConfig(config, configPath) {
1741
1896
  pkgJson,
1742
1897
  userExternals: config.output?.externals
1743
1898
  });
1744
- const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath));
1899
+ const { entryConfig, lcp } = await composeEntryConfig(config.source?.entry, config.bundle, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath), cssModulesAuto);
1900
+ const cssConfig = composeCssConfig(lcp, config.bundle);
1745
1901
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
1746
1902
  const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1747
1903
  const minifyConfig = composeMinifyConfig(config.output?.minify);
1748
1904
  const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
1749
1905
  const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
1750
- return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1906
+ return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, cssConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1751
1907
  }
1752
1908
  async function composeCreateRsbuildConfig(rslibConfig, path) {
1753
1909
  const constantRsbuildConfig = await createConstantRsbuildConfig();
@@ -1782,6 +1938,7 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
1782
1938
  'format',
1783
1939
  'autoExtension',
1784
1940
  'autoExternal',
1941
+ 'redirect',
1785
1942
  'syntax',
1786
1943
  'externalHelpers',
1787
1944
  'banner',
@@ -1827,7 +1984,7 @@ const applyCommonOptions = (command)=>{
1827
1984
  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');
1828
1985
  };
1829
1986
  function runCli() {
1830
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.0.9");
1987
+ __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.0.11");
1831
1988
  const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('build');
1832
1989
  const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('inspect');
1833
1990
  [
@@ -1869,6 +2026,6 @@ function runCli() {
1869
2026
  });
1870
2027
  __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.parse();
1871
2028
  }
1872
- const src_version = "0.0.9";
2029
+ const src_version = "0.0.11";
1873
2030
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger;
1874
2031
  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,2 +1,2 @@
1
- import { type RsbuildPlugin } from '@rsbuild/core';
1
+ import type { RsbuildPlugin } from '@rsbuild/core';
2
2
  export declare const pluginCjsShim: () => RsbuildPlugin;
@@ -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.9",
3
+ "version": "0.0.11",
4
4
  "description": "The Rspack-based library build tool.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -32,10 +32,11 @@
32
32
  "compiled"
33
33
  ],
34
34
  "dependencies": {
35
- "@rsbuild/core": "1.0.10",
36
- "rsbuild-plugin-dts": "0.0.9"
35
+ "@rsbuild/core": "1.0.12",
36
+ "rsbuild-plugin-dts": "0.0.11"
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",
@@ -43,10 +44,10 @@
43
44
  "memfs": "^4.13.0",
44
45
  "picocolors": "1.1.0",
45
46
  "prebundle": "1.2.2",
46
- "rslib": "npm:@rslib/core@0.0.8",
47
+ "rslib": "npm:@rslib/core@0.0.10",
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": {