@rslib/core 0.0.17 → 0.1.0

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.
@@ -0,0 +1,53 @@
1
+ const RSLIB_ENTRY_QUERY = '__rslib_entry__';
2
+ const SHEBANG_REGEX = /#!.*[\s\n\r]*$/;
3
+ const REACT_DIRECTIVE_REGEX = /^['"]use (client|server)['"](;?)[\s\n\r]*$/;
4
+ const JS_EXTENSIONS = [
5
+ 'js',
6
+ 'mjs',
7
+ 'jsx',
8
+ 'ts',
9
+ 'mts',
10
+ 'tsx',
11
+ 'cjs',
12
+ 'cjsx',
13
+ 'mjsx',
14
+ 'mtsx',
15
+ 'cts',
16
+ 'ctsx'
17
+ ];
18
+ const CSS_EXTENSIONS = [
19
+ 'css',
20
+ 'sass',
21
+ 'scss',
22
+ 'less'
23
+ ];
24
+ const ENTRY_EXTENSIONS = [
25
+ ...JS_EXTENSIONS,
26
+ ...CSS_EXTENSIONS
27
+ ];
28
+ new RegExp(`\\.(${JS_EXTENSIONS.join('|')})$`);
29
+ new RegExp(`\\.(${CSS_EXTENSIONS.join('|')})$`);
30
+ new RegExp(`\\.(${ENTRY_EXTENSIONS.join('|')})$`);
31
+ function splitFromFirstLine(text) {
32
+ const match = text.match(/(\r\n|\n)/);
33
+ if (!match) return [
34
+ text,
35
+ ''
36
+ ];
37
+ return [
38
+ text.slice(0, match.index),
39
+ text.slice(match.index)
40
+ ];
41
+ }
42
+ const entryModuleLoader_loader = function(source) {
43
+ let result = source;
44
+ if (this.resourceQuery === `?${RSLIB_ENTRY_QUERY}`) {
45
+ const [firstLine1, rest] = splitFromFirstLine(result);
46
+ if (SHEBANG_REGEX.test(firstLine1)) result = rest;
47
+ const [firstLine2, rest2] = splitFromFirstLine(result);
48
+ if (REACT_DIRECTIVE_REGEX.test(firstLine2)) result = rest2;
49
+ }
50
+ return result;
51
+ };
52
+ /* ESM default export */ const entryModuleLoader = entryModuleLoader_loader;
53
+ export { entryModuleLoader as default };
package/dist/index.js CHANGED
@@ -3,8 +3,8 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises__ from "node:fs/promises";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__ from "../compiled/picocolors/index.js";
6
- import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
7
6
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__ from "../compiled/commander/index.js";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
8
8
  import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
9
9
  import * as __WEBPACK_EXTERNAL_MODULE_node_module__ from "node:module";
10
10
  import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
@@ -91,6 +91,9 @@ async function calcLongestCommonPath(absPaths) {
91
91
  if (stats?.isFile()) lca = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname(lca);
92
92
  return lca;
93
93
  }
94
+ function getAbsolutePath(base, filepath) {
95
+ return (0, __WEBPACK_EXTERNAL_MODULE_node_path__.isAbsolute)(filepath) ? filepath : (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(base, filepath);
96
+ }
94
97
  const readPackageJson = (rootPath)=>{
95
98
  const pkgJsonPath = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].join(rootPath, './package.json');
96
99
  if (!__WEBPACK_EXTERNAL_MODULE_node_fs__["default"].existsSync(pkgJsonPath)) {
@@ -118,8 +121,9 @@ function omit(obj, keysObj) {
118
121
  return ret;
119
122
  }, {});
120
123
  }
121
- function isPluginIncluded(config, pluginName) {
122
- return Boolean(config.plugins?.some((plugin)=>{
124
+ function isPluginIncluded(pluginName, plugins) {
125
+ return Boolean(plugins?.some((plugin)=>{
126
+ if (Array.isArray(plugin)) return isPluginIncluded(pluginName, plugin);
123
127
  if ('object' == typeof plugin && null !== plugin && 'name' in plugin) return plugin.name === pluginName;
124
128
  return false;
125
129
  }));
@@ -127,7 +131,7 @@ function isPluginIncluded(config, pluginName) {
127
131
  function checkMFPlugin(config) {
128
132
  if ('mf' !== config.format) return true;
129
133
  // https://github.com/module-federation/core/blob/4e5c4b96ee45899f3ba5904b8927768980d5ad0e/packages/rsbuild-plugin/src/cli/index.ts#L17
130
- const added = isPluginIncluded(config, 'rsbuild:module-federation-enhanced');
134
+ const added = isPluginIncluded('rsbuild:module-federation-enhanced', config.plugins);
131
135
  if (!added) {
132
136
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.warn(`${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].green('format: "mf"')} should be used with ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].blue('@module-federation/rsbuild-plugin')}", consider installing and adding it to plugins. Check the documentation (https://module-federation.io/guide/basic/rsbuild.html#rslib-module) to get started with "mf" output.`);
133
137
  process.exit(1);
@@ -150,7 +154,7 @@ function prepareCli() {
150
154
  // Some package managers automatically output a blank line, some do not.
151
155
  const { npm_execpath } = process.env;
152
156
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
153
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.0.17\n`);
157
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.1.0\n`);
154
158
  }
155
159
  const DEFAULT_CONFIG_NAME = 'rslib.config';
156
160
  const DEFAULT_CONFIG_EXTENSIONS = [
@@ -162,6 +166,10 @@ const DEFAULT_CONFIG_EXTENSIONS = [
162
166
  '.cts'
163
167
  ];
164
168
  const SWC_HELPERS = '@swc/helpers';
169
+ const RSLIB_ENTRY_QUERY = '__rslib_entry__';
170
+ const SHEBANG_PREFIX = '#!';
171
+ const SHEBANG_REGEX = /#!.*[\s\n\r]*$/;
172
+ const REACT_DIRECTIVE_REGEX = /^['"]use (client|server)['"](;?)[\s\n\r]*$/;
165
173
  const JS_EXTENSIONS = [
166
174
  'js',
167
175
  'mjs',
@@ -258,9 +266,9 @@ function cssExternalHandler(request, callback, jsExtension, auto, isStyleRedirec
258
266
  }
259
267
  return false;
260
268
  }
261
- const cssConfig_pluginName = 'rsbuild:lib-css';
269
+ const PLUGIN_NAME = 'rsbuild:lib-css';
262
270
  const pluginLibCss = (rootDir)=>({
263
- name: cssConfig_pluginName,
271
+ name: PLUGIN_NAME,
264
272
  setup (api) {
265
273
  api.modifyBundlerChain((config, { CHAIN_ID })=>{
266
274
  let isUsingCssExtract = false;
@@ -305,12 +313,14 @@ const composeCssConfig = (rootDir, bundle = true)=>{
305
313
  }
306
314
  };
307
315
  };
308
- const importMetaUrlShim = `/*#__PURE__*/ (function () {
316
+ // The shim will be injected in PostEntryPlugin.
317
+ const importMetaUrlShim = `const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
309
318
  return typeof document === 'undefined'
310
- ? new (module.require('url'.replace('', '')).URL)('file:' + __filename).href
319
+ ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
311
320
  : (document.currentScript && document.currentScript.src) ||
312
321
  new URL('main.js', document.baseURI).href;
313
- })()`;
322
+ })();
323
+ `;
314
324
  // This Rsbuild plugin will shim `import.meta.url` for CommonJS modules.
315
325
  // - Replace `import.meta.url` with `importMetaUrl`.
316
326
  // - Inject `importMetaUrl` to the end of the module (can't inject at the beginning because of `"use strict";`).
@@ -321,7 +331,7 @@ const pluginCjsImportMetaUrlShim = ()=>({
321
331
  api.modifyEnvironmentConfig((config)=>{
322
332
  config.source.define = {
323
333
  ...config.source.define,
324
- 'import.meta.url': importMetaUrlShim
334
+ 'import.meta.url': '__rslib_import_meta_url__'
325
335
  };
326
336
  });
327
337
  }
@@ -345,6 +355,125 @@ const pluginEsmRequireShim = ()=>({
345
355
  });
346
356
  }
347
357
  });
358
+ const EntryChunkPlugin_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module__.createRequire)(import.meta.url);
359
+ const EntryChunkPlugin_PLUGIN_NAME = 'rsbuild:lib-entry-chunk';
360
+ const LOADER_NAME = 'rsbuild:lib-entry-module';
361
+ const matchFirstLine = (source, regex)=>{
362
+ const lineBreakPos = source.match(/(\r\n|\n)/);
363
+ const firstLineContent = source.slice(0, lineBreakPos?.index);
364
+ const matched = regex.exec(firstLineContent);
365
+ if (!matched) return false;
366
+ return matched[0];
367
+ };
368
+ class EntryChunkPlugin {
369
+ reactDirectives = {};
370
+ shebangChmod = 493;
371
+ shebangEntries = {};
372
+ shebangInjectedAssets = new Set();
373
+ enabledImportMetaUrlShim;
374
+ constructor({ enabledImportMetaUrlShim = true }){
375
+ this.enabledImportMetaUrlShim = enabledImportMetaUrlShim;
376
+ }
377
+ apply(compiler) {
378
+ compiler.hooks.entryOption.tap(EntryChunkPlugin_PLUGIN_NAME, (_context, entries)=>{
379
+ for(const name in entries){
380
+ const entry = entries[name];
381
+ if (!entry) continue;
382
+ let first;
383
+ if (Array.isArray(entry)) first = entry[0];
384
+ else if (Array.isArray(entry.import)) first = entry.import[0];
385
+ else if ('string' == typeof entry) first = entry;
386
+ if ('string' != typeof first) continue;
387
+ const filename = first.split('?')[0];
388
+ const isJs = JS_EXTENSIONS_PATTERN.test(filename);
389
+ if (!isJs) continue;
390
+ const content = compiler.inputFileSystem.readFileSync(filename, {
391
+ encoding: 'utf-8'
392
+ });
393
+ // Shebang
394
+ if (content.startsWith(SHEBANG_PREFIX)) {
395
+ const shebangMatch = matchFirstLine(content, SHEBANG_REGEX);
396
+ if (shebangMatch) this.shebangEntries[name] = shebangMatch;
397
+ }
398
+ // React directive
399
+ const reactDirective = matchFirstLine(content, REACT_DIRECTIVE_REGEX);
400
+ if (reactDirective) this.reactDirectives[name] = reactDirective;
401
+ }
402
+ });
403
+ compiler.hooks.thisCompilation.tap(EntryChunkPlugin_PLUGIN_NAME, (compilation)=>{
404
+ compilation.hooks.chunkAsset.tap(EntryChunkPlugin_PLUGIN_NAME, (chunk, filename)=>{
405
+ const isJs = JS_EXTENSIONS_PATTERN.test(filename);
406
+ if (!isJs) return;
407
+ const name = chunk.name;
408
+ if (!name) return;
409
+ const shebangEntry = this.shebangEntries[name];
410
+ if (shebangEntry) this.shebangEntries[filename] = shebangEntry;
411
+ const reactDirective = this.reactDirectives[name];
412
+ if (reactDirective) this.reactDirectives[filename] = reactDirective;
413
+ });
414
+ });
415
+ compiler.hooks.make.tap(EntryChunkPlugin_PLUGIN_NAME, (compilation)=>{
416
+ compilation.hooks.processAssets.tap(EntryChunkPlugin_PLUGIN_NAME, (assets)=>{
417
+ if (!this.enabledImportMetaUrlShim) return;
418
+ const chunkAsset = Object.keys(assets).filter((name)=>JS_EXTENSIONS_PATTERN.test(name));
419
+ for (const name of chunkAsset)compilation.updateAsset(name, (old)=>{
420
+ const oldSource = old.source().toString();
421
+ const replaceSource = new __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.sources.ReplaceSource(old);
422
+ if (oldSource.startsWith('use strict;') || oldSource.startsWith('"use strict";')) replaceSource.replace(0, 11, `"use strict";\n${importMetaUrlShim}`);
423
+ else replaceSource.insert(0, importMetaUrlShim);
424
+ return replaceSource;
425
+ });
426
+ });
427
+ compilation.hooks.processAssets.tap({
428
+ name: EntryChunkPlugin_PLUGIN_NAME,
429
+ // Just after minify stage, to avoid from being minified.
430
+ stage: __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING - 1
431
+ }, (assets)=>{
432
+ const chunkAsset = Object.keys(assets);
433
+ for (const name of chunkAsset){
434
+ const shebangValue = this.shebangEntries[name];
435
+ const reactDirectiveValue = this.reactDirectives[name];
436
+ if (shebangValue || reactDirectiveValue) compilation.updateAsset(name, (old)=>{
437
+ const replaceSource = new __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.rspack.sources.ReplaceSource(old);
438
+ // Shebang
439
+ if (shebangValue) {
440
+ replaceSource.insert(0, `${shebangValue}\n`);
441
+ this.shebangInjectedAssets.add(name);
442
+ }
443
+ // React directives
444
+ if (reactDirectiveValue) replaceSource.insert(0, `${reactDirectiveValue}\n`);
445
+ return replaceSource;
446
+ });
447
+ }
448
+ });
449
+ });
450
+ compiler.hooks.assetEmitted.tap(EntryChunkPlugin_PLUGIN_NAME, (file, { targetPath })=>{
451
+ if (this.shebangInjectedAssets.has(file)) (0, __WEBPACK_EXTERNAL_MODULE_node_fs__.chmodSync)(targetPath, this.shebangChmod);
452
+ });
453
+ }
454
+ }
455
+ const entryModuleLoaderRsbuildPlugin = ()=>({
456
+ name: EntryChunkPlugin_PLUGIN_NAME,
457
+ setup (api) {
458
+ api.modifyBundlerChain((config, { CHAIN_ID })=>{
459
+ config.module.rule(CHAIN_ID.RULE.JS).use(LOADER_NAME).loader(EntryChunkPlugin_require.resolve('./entryModuleLoader.js'));
460
+ });
461
+ }
462
+ });
463
+ const composeEntryChunkConfig = ({ enabledImportMetaUrlShim })=>({
464
+ plugins: [
465
+ entryModuleLoaderRsbuildPlugin()
466
+ ],
467
+ tools: {
468
+ rspack: {
469
+ plugins: [
470
+ new EntryChunkPlugin({
471
+ enabledImportMetaUrlShim
472
+ })
473
+ ]
474
+ }
475
+ }
476
+ });
348
477
  const getDefaultExtension = (options)=>{
349
478
  const { format, pkgJson, autoExtension } = options;
350
479
  let jsExtension = '.js';
@@ -1564,7 +1693,10 @@ async function createConstantRsbuildConfig() {
1564
1693
  target: 'node',
1565
1694
  filenameHash: false,
1566
1695
  distPath: {
1567
- js: './'
1696
+ js: './',
1697
+ jsAsync: './',
1698
+ css: './',
1699
+ cssAsync: './'
1568
1700
  }
1569
1701
  }
1570
1702
  });
@@ -1673,7 +1805,6 @@ const composeFormatConfig = ({ format, bundle = true, umdName, pkgJson })=>{
1673
1805
  output: {
1674
1806
  uniqueName: pkgJson.name
1675
1807
  },
1676
- // TODO when we provide dev mode for rslib mf format, this should be modified to as the same with config.mode
1677
1808
  // can not set nodeEnv to false, because mf format should build shared module.
1678
1809
  // If nodeEnv is false, the process.env.NODE_ENV in third-party packages's will not be replaced
1679
1810
  // now we have not provide dev mode for users, so we can always set nodeEnv as 'production'
@@ -1681,6 +1812,9 @@ const composeFormatConfig = ({ format, bundle = true, umdName, pkgJson })=>{
1681
1812
  nodeEnv: 'production'
1682
1813
  }
1683
1814
  }
1815
+ },
1816
+ output: {
1817
+ target: 'web'
1684
1818
  }
1685
1819
  };
1686
1820
  default:
@@ -1698,9 +1832,20 @@ const composeShimsConfig = (format, shims)=>{
1698
1832
  require: shims?.esm?.require ?? false
1699
1833
  }
1700
1834
  };
1835
+ const enabledShims = {
1836
+ cjs: 'cjs' === format ? resolvedShims.cjs : {
1837
+ 'import.meta.url': false
1838
+ },
1839
+ esm: 'esm' === format ? resolvedShims.esm : {
1840
+ __filename: false,
1841
+ __dirname: false,
1842
+ require: false
1843
+ }
1844
+ };
1845
+ let rsbuildConfig = {};
1701
1846
  switch(format){
1702
1847
  case 'esm':
1703
- return {
1848
+ rsbuildConfig = {
1704
1849
  tools: {
1705
1850
  rspack: {
1706
1851
  node: {
@@ -1714,19 +1859,24 @@ const composeShimsConfig = (format, shims)=>{
1714
1859
  resolvedShims.esm.require && pluginEsmRequireShim()
1715
1860
  ].filter(Boolean)
1716
1861
  };
1862
+ break;
1717
1863
  case 'cjs':
1718
- return {
1864
+ rsbuildConfig = {
1719
1865
  plugins: [
1720
1866
  resolvedShims.cjs['import.meta.url'] && pluginCjsImportMetaUrlShim()
1721
1867
  ].filter(Boolean)
1722
1868
  };
1869
+ break;
1723
1870
  case 'umd':
1724
- return {};
1725
1871
  case 'mf':
1726
- return {};
1872
+ break;
1727
1873
  default:
1728
1874
  throw new Error(`Unsupported format: ${format}`);
1729
1875
  }
1876
+ return {
1877
+ rsbuildConfig,
1878
+ enabledShims
1879
+ };
1730
1880
  };
1731
1881
  const composeModuleImportWarn = (request)=>`The externalized commonjs request ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].green(`"${request}"`)} will use ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].blue('"module"')} external type in ESM format. If you want to specify other external type, considering set the request and type with ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].blue('"output.externals"')}.`;
1732
1882
  const composeExternalsConfig = (format, externals)=>{
@@ -1735,7 +1885,7 @@ const composeExternalsConfig = (format, externals)=>{
1735
1885
  // should to be unified and merged together in the future.
1736
1886
  const externalsTypeMap = {
1737
1887
  esm: 'module-import',
1738
- cjs: 'commonjs',
1888
+ cjs: 'commonjs-import',
1739
1889
  umd: 'umd',
1740
1890
  // If use 'var', when projects import an external package like '@pkg', this will cause a syntax error such as 'var pkg = @pkg'.
1741
1891
  // If use 'umd', the judgement conditions may be affected by other packages that define variables like 'define'.
@@ -1767,16 +1917,18 @@ const composeAutoExtensionConfig = (config, autoExtension, pkgJson)=>{
1767
1917
  pkgJson,
1768
1918
  autoExtension
1769
1919
  });
1770
- return {
1771
- config: {
1772
- output: {
1773
- filename: {
1774
- js: `[name]${jsExtension}`,
1775
- ...config.output?.filename
1776
- }
1920
+ const updatedConfig = {
1921
+ output: {
1922
+ filename: {
1923
+ js: `[name]${jsExtension}`,
1924
+ ...config.output?.filename
1777
1925
  }
1778
- },
1779
- jsExtension,
1926
+ }
1927
+ };
1928
+ const updatedJsExtension = 'string' == typeof updatedConfig.output?.filename?.js && updatedConfig.output?.filename?.js ? (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(updatedConfig.output.filename.js) : jsExtension;
1929
+ return {
1930
+ config: updatedConfig,
1931
+ jsExtension: updatedJsExtension,
1780
1932
  dtsExtension
1781
1933
  };
1782
1934
  };
@@ -1807,6 +1959,11 @@ const composeSyntaxConfig = (target, syntax)=>{
1807
1959
  }
1808
1960
  };
1809
1961
  };
1962
+ const appendEntryQuery = (entry)=>{
1963
+ const newEntry = {};
1964
+ for(const key in entry)newEntry[key] = `${entry[key]}?${RSLIB_ENTRY_QUERY}`;
1965
+ return newEntry;
1966
+ };
1810
1967
  const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
1811
1968
  if (!entries) return {
1812
1969
  entryConfig: {},
@@ -1815,7 +1972,7 @@ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
1815
1972
  if (false !== bundle) return {
1816
1973
  entryConfig: {
1817
1974
  source: {
1818
- entry: entries
1975
+ entry: appendEntryQuery(entries)
1819
1976
  }
1820
1977
  },
1821
1978
  lcp: null
@@ -1862,7 +2019,7 @@ const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
1862
2019
  const lcp = await calcLongestCommonPath(Object.values(resolvedEntries));
1863
2020
  const entryConfig = {
1864
2021
  source: {
1865
- entry: resolvedEntries
2022
+ entry: appendEntryQuery(resolvedEntries)
1866
2023
  }
1867
2024
  };
1868
2025
  return {
@@ -1895,7 +2052,8 @@ const composeBundleConfig = (jsExtension, redirect, cssModulesAuto, bundle)=>{
1895
2052
  if (!JS_EXTENSIONS_PATTERN.test(request)) // If it does not match jsExtensionsPattern, we should do nothing, eg: ./foo.png
1896
2053
  return callback();
1897
2054
  request = request.replace(/\.[^.]+$/, jsExtension);
1898
- } else request = `${request}${jsExtension}`;
2055
+ } else // TODO: add redirect.extension option
2056
+ request = `${request}${jsExtension}`;
1899
2057
  }
1900
2058
  return callback(null, request);
1901
2059
  }
@@ -1906,7 +2064,7 @@ const composeBundleConfig = (jsExtension, redirect, cssModulesAuto, bundle)=>{
1906
2064
  };
1907
2065
  };
1908
2066
  const composeDtsConfig = async (libConfig, dtsExtension)=>{
1909
- const { output, autoExternal, banner, footer } = libConfig;
2067
+ const { autoExternal, banner, footer } = libConfig;
1910
2068
  let { dts } = libConfig;
1911
2069
  if (false === dts || void 0 === dts) return {};
1912
2070
  // DTS default to bundleless whether js is bundle or not
@@ -1918,10 +2076,10 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1918
2076
  plugins: [
1919
2077
  pluginDts({
1920
2078
  // Only setting ⁠dts.bundle to true will generate the bundled d.ts.
1921
- bundle: dts?.bundle ?? false,
1922
- distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
1923
- build: dts?.build ?? false,
1924
- abortOnError: dts?.abortOnError ?? true,
2079
+ bundle: dts?.bundle,
2080
+ distPath: dts?.distPath,
2081
+ build: dts?.build,
2082
+ abortOnError: dts?.abortOnError,
1925
2083
  dtsExtension: dts?.autoExtension ? dtsExtension : '.d.ts',
1926
2084
  autoExternal,
1927
2085
  banner: banner?.dts,
@@ -1930,8 +2088,10 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1930
2088
  ]
1931
2089
  };
1932
2090
  };
1933
- const composeTargetConfig = (target = 'node')=>{
1934
- switch(target){
2091
+ const composeTargetConfig = (target, format)=>{
2092
+ let defaultTarget = target;
2093
+ if (!defaultTarget) defaultTarget = 'mf' === format ? 'web' : 'node';
2094
+ switch(defaultTarget){
1935
2095
  case 'web':
1936
2096
  return {
1937
2097
  config: {
@@ -1975,7 +2135,7 @@ const composeTargetConfig = (target = 'node')=>{
1975
2135
  // },
1976
2136
  // };
1977
2137
  default:
1978
- throw new Error(`Unsupported platform: ${target}`);
2138
+ throw new Error(`Unsupported platform: ${defaultTarget}`);
1979
2139
  }
1980
2140
  };
1981
2141
  const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
@@ -2006,14 +2166,15 @@ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
2006
2166
  }
2007
2167
  return defaultConfig;
2008
2168
  };
2009
- async function composeLibRsbuildConfig(config, configPath) {
2169
+ async function composeLibRsbuildConfig(config) {
2010
2170
  checkMFPlugin(config);
2011
- const rootPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath);
2171
+ // Get the absolute path of the root directory to align with Rsbuild's default behavior
2172
+ const rootPath = config.root ? getAbsolutePath(process.cwd(), config.root) : process.cwd();
2012
2173
  const pkgJson = readPackageJson(rootPath);
2013
2174
  const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
2014
2175
  const cssModulesAuto = config.output?.cssModules?.auto ?? true;
2015
2176
  const { format, shims, bundle = true, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false, redirect = {}, umdName } = config;
2016
- const shimsConfig = composeShimsConfig(format, shims);
2177
+ const { rsbuildConfig: shimsConfig, enabledShims } = composeShimsConfig(format, shims);
2017
2178
  const formatConfig = composeFormatConfig({
2018
2179
  format: format,
2019
2180
  pkgJson: pkgJson,
@@ -2024,32 +2185,34 @@ async function composeLibRsbuildConfig(config, configPath) {
2024
2185
  const externalsConfig = composeExternalsConfig(format, config.output?.externals);
2025
2186
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
2026
2187
  const bundleConfig = composeBundleConfig(jsExtension, redirect, cssModulesAuto, bundle);
2027
- const { config: targetConfig, target } = composeTargetConfig(config.output?.target);
2188
+ const { config: targetConfig, target } = composeTargetConfig(config.output?.target, format);
2028
2189
  const syntaxConfig = composeSyntaxConfig(target, config?.syntax);
2029
2190
  const autoExternalConfig = composeAutoExternalConfig({
2030
2191
  autoExternal,
2031
2192
  pkgJson,
2032
2193
  userExternals: config.output?.externals
2033
2194
  });
2034
- const { entryConfig, lcp } = await composeEntryConfig(config.source?.entry, config.bundle, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(configPath), cssModulesAuto);
2195
+ const { entryConfig, lcp } = await composeEntryConfig(config.source?.entry, config.bundle, rootPath, cssModulesAuto);
2035
2196
  const cssConfig = composeCssConfig(lcp, config.bundle);
2197
+ const entryChunkConfig = composeEntryChunkConfig({
2198
+ enabledImportMetaUrlShim: enabledShims.cjs['import.meta.url']
2199
+ });
2036
2200
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
2037
2201
  const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
2038
2202
  const minifyConfig = composeMinifyConfig(config);
2039
2203
  const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
2040
2204
  const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
2041
- return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, shimsConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, cssConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
2205
+ return (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(formatConfig, shimsConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, cssConfig, entryChunkConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
2042
2206
  }
2043
- async function composeCreateRsbuildConfig(rslibConfig, path) {
2207
+ async function composeCreateRsbuildConfig(rslibConfig) {
2044
2208
  const constantRsbuildConfig = await createConstantRsbuildConfig();
2045
- const configPath = path ?? rslibConfig._privateMeta?.configFilePath;
2046
2209
  const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
2047
2210
  if (!libConfigsArray) throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
2048
2211
  const libConfigPromises = libConfigsArray.map(async (libConfig)=>{
2049
2212
  const userConfig = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(sharedRsbuildConfig, libConfig);
2050
2213
  // Merge the configuration of each environment based on the shared Rsbuild
2051
2214
  // configuration and Lib configuration in the settings.
2052
- const libRsbuildConfig = await composeLibRsbuildConfig(userConfig, configPath);
2215
+ const libRsbuildConfig = await composeLibRsbuildConfig(userConfig);
2053
2216
  // Reset certain fields because they will be completely overridden by the upcoming merge.
2054
2217
  // We don't want to retain them in the final configuration.
2055
2218
  // The reset process should occur after merging the library configuration.
@@ -2058,7 +2221,7 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
2058
2221
  // Already manually sort and merge the externals configuration.
2059
2222
  userConfig.output ??= {};
2060
2223
  delete userConfig.output.externals;
2061
- return {
2224
+ const config = {
2062
2225
  format: libConfig.format,
2063
2226
  // The merge order represents the priority of the configuration
2064
2227
  // The priorities from high to low are as follows:
@@ -2069,6 +2232,7 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
2069
2232
  // In compose process of 2, we may read some config from 1, and reassemble the related config,
2070
2233
  // so before final mergeRsbuildConfig, we reset some specified fields
2071
2234
  config: (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.mergeRsbuildConfig)(constantRsbuildConfig, libRsbuildConfig, omit(userConfig, {
2235
+ id: true,
2072
2236
  bundle: true,
2073
2237
  format: true,
2074
2238
  autoExtension: true,
@@ -2083,43 +2247,75 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
2083
2247
  umdName: true
2084
2248
  }))
2085
2249
  };
2250
+ if ('string' == typeof libConfig.id) config.id = libConfig.id;
2251
+ return config;
2086
2252
  });
2087
2253
  const composedRsbuildConfig = await Promise.all(libConfigPromises);
2088
2254
  return composedRsbuildConfig;
2089
2255
  }
2090
2256
  async function composeRsbuildEnvironments(rslibConfig) {
2091
- const rsbuildConfigObject = await composeCreateRsbuildConfig(rslibConfig);
2257
+ const rsbuildConfigWithLibInfo = await composeCreateRsbuildConfig(rslibConfig);
2258
+ // User provided ids should take precedence over generated ids.
2259
+ const usedIds = rsbuildConfigWithLibInfo.map(({ id })=>id).filter(Boolean);
2092
2260
  const environments = {};
2093
- const formatCount = rsbuildConfigObject.reduce((acc, { format })=>{
2261
+ const formatCount = rsbuildConfigWithLibInfo.reduce((acc, { format })=>{
2094
2262
  acc[format] = (acc[format] ?? 0) + 1;
2095
2263
  return acc;
2096
2264
  }, {});
2097
- const formatIndex = {
2098
- esm: 0,
2099
- cjs: 0,
2100
- umd: 0,
2101
- mf: 0
2265
+ const composeDefaultId = (format)=>{
2266
+ const nextDefaultId = (format, index)=>`${format}${1 === formatCount[format] && 0 === index ? '' : index}`;
2267
+ let index = 0;
2268
+ let candidateId = nextDefaultId(format, index);
2269
+ while(-1 !== usedIds.indexOf(candidateId))candidateId = nextDefaultId(format, ++index);
2270
+ usedIds.push(candidateId);
2271
+ return candidateId;
2102
2272
  };
2103
- for (const { format, config } of rsbuildConfigObject){
2104
- const currentFormatCount = formatCount[format];
2105
- const currentFormatIndex = formatIndex[format]++;
2106
- environments[1 === currentFormatCount ? format : `${format}${currentFormatIndex}`] = config;
2273
+ for (const { format, id, config } of rsbuildConfigWithLibInfo){
2274
+ const libId = 'string' == typeof id ? id : composeDefaultId(format);
2275
+ environments[libId] = config;
2107
2276
  }
2277
+ const conflictIds = usedIds.filter((id, index)=>usedIds.indexOf(id) !== index);
2278
+ if (conflictIds.length) throw new Error(`The following ids are duplicated: ${conflictIds.map((id)=>`"${id}"`).join(', ')}. Please change the "lib.id" to be unique.`);
2108
2279
  return environments;
2109
2280
  }
2110
2281
  const pruneEnvironments = (environments, libs)=>{
2111
2282
  if (!libs) return environments;
2112
2283
  return Object.fromEntries(Object.entries(environments).filter(([name])=>libs.includes(name)));
2113
2284
  };
2114
- async function build(config, options) {
2285
+ async function build(config, options = {}) {
2115
2286
  const environments = await composeRsbuildEnvironments(config);
2116
2287
  const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
2117
2288
  rsbuildConfig: {
2118
- environments: pruneEnvironments(environments, options?.lib)
2289
+ environments: pruneEnvironments(environments, options.lib)
2119
2290
  }
2120
2291
  });
2121
2292
  await rsbuildInstance.build({
2122
- watch: options?.watch
2293
+ watch: options.watch
2294
+ });
2295
+ return rsbuildInstance;
2296
+ }
2297
+ async function loadRslibConfig(options) {
2298
+ const cwd = process.cwd();
2299
+ const root = options.root ? getAbsolutePath(cwd, options.root) : cwd;
2300
+ const rslibConfig = await loadConfig({
2301
+ cwd: root,
2302
+ path: options.config,
2303
+ envMode: options.envMode
2304
+ });
2305
+ return rslibConfig;
2306
+ }
2307
+ async function inspect(config, options = {}) {
2308
+ const environments = await composeRsbuildEnvironments(config);
2309
+ const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
2310
+ rsbuildConfig: {
2311
+ environments: pruneEnvironments(environments, options.lib)
2312
+ }
2313
+ });
2314
+ await rsbuildInstance.inspectConfig({
2315
+ mode: options.mode,
2316
+ verbose: options.verbose,
2317
+ outputPath: options.output,
2318
+ writeToDisk: true
2123
2319
  });
2124
2320
  return rsbuildInstance;
2125
2321
  }
@@ -2155,13 +2351,13 @@ function changeEnvToDev(rsbuildConfig) {
2155
2351
  });
2156
2352
  }
2157
2353
  const applyCommonOptions = (command)=>{
2158
- 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');
2354
+ command.option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path').option('-r --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file');
2159
2355
  };
2160
2356
  const repeatableOption = (value, previous)=>(previous ?? []).concat([
2161
2357
  value
2162
2358
  ]);
2163
2359
  function runCli() {
2164
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.0.17");
2360
+ __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.1.0");
2165
2361
  const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('build');
2166
2362
  const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('inspect');
2167
2363
  const mfDevCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('mf dev');
@@ -2170,37 +2366,28 @@ function runCli() {
2170
2366
  inspectCommand,
2171
2367
  mfDevCommand
2172
2368
  ].forEach(applyCommonOptions);
2173
- buildCommand.option('--lib <name>', 'build the specified library (may be repeated)', repeatableOption).option('-w --watch', 'turn on watch mode, watch for changes and rebuild').description('build the library for production').action(async (options)=>{
2369
+ buildCommand.option('--lib <id>', 'build the specified library (may be repeated)', repeatableOption).option('-w --watch', 'turn on watch mode, watch for changes and rebuild').description('build the library for production').action(async (options)=>{
2174
2370
  try {
2175
- const rslibConfig = await loadConfig({
2176
- path: options.config,
2177
- envMode: options.envMode
2371
+ const rslibConfig = await loadRslibConfig(options);
2372
+ await build(rslibConfig, {
2373
+ lib: options.lib,
2374
+ watch: options.watch
2178
2375
  });
2179
- await build(rslibConfig, options);
2180
2376
  } catch (err) {
2181
2377
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error('Failed to build.');
2182
2378
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error(err);
2183
2379
  process.exit(1);
2184
2380
  }
2185
2381
  });
2186
- inspectCommand.description('inspect the Rsbuild / Rspack configs of Rslib projects').option('--lib <name>', 'inspect the specified library (may be repeated)', repeatableOption).option('--output <output>', 'specify inspect content output path', '.rsbuild').option('--verbose', 'show full function definitions in output').action(async (options)=>{
2382
+ inspectCommand.description('inspect the Rsbuild / Rspack configs of Rslib projects').option('--lib <id>', 'inspect the specified library (may be repeated)', repeatableOption).option('--output <output>', 'specify inspect content output path', '.rsbuild').option('--verbose', 'show full function definitions in output').action(async (options)=>{
2187
2383
  try {
2188
2384
  // TODO: inspect should output Rslib's config
2189
- const rslibConfig = await loadConfig({
2190
- path: options.config,
2191
- envMode: options.envMode
2192
- });
2193
- const environments = await composeRsbuildEnvironments(rslibConfig);
2194
- const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
2195
- rsbuildConfig: {
2196
- environments: pruneEnvironments(environments, options.lib)
2197
- }
2198
- });
2199
- await rsbuildInstance.inspectConfig({
2385
+ const rslibConfig = await loadRslibConfig(options);
2386
+ await inspect(rslibConfig, {
2387
+ lib: options.lib,
2200
2388
  mode: options.mode,
2201
- verbose: options.verbose,
2202
- outputPath: options.output,
2203
- writeToDisk: true
2389
+ output: options.output,
2390
+ verbose: options.verbose
2204
2391
  });
2205
2392
  } catch (err) {
2206
2393
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error('Failed to inspect config.');
@@ -2210,10 +2397,8 @@ function runCli() {
2210
2397
  });
2211
2398
  mfDevCommand.description('start Rsbuild dev server of Module Federation format').action(async (options)=>{
2212
2399
  try {
2213
- const rslibConfig = await loadConfig({
2214
- path: options.config,
2215
- envMode: options.envMode
2216
- });
2400
+ const rslibConfig = await loadRslibConfig(options);
2401
+ // TODO: support lib option in mf dev server
2217
2402
  await startMFDevServer(rslibConfig);
2218
2403
  } catch (err) {
2219
2404
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error('Failed to start mf dev.');
@@ -2223,6 +2408,6 @@ function runCli() {
2223
2408
  });
2224
2409
  __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.parse();
2225
2410
  }
2226
- const src_version = "0.0.17";
2411
+ const src_version = "0.1.0";
2227
2412
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger;
2228
- export { build, defineConfig, loadConfig, prepareCli, runCli, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_version as version, __webpack_exports__logger as logger };
2413
+ export { build, defineConfig, inspect, loadConfig, prepareCli, runCli, startMFDevServer, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_version as version, __webpack_exports__logger as logger };
@@ -0,0 +1,4 @@
1
+ import { type RsbuildInstance } from '@rsbuild/core';
2
+ import type { RslibConfig } from '../types/config';
3
+ import type { BuildOptions } from './commands';
4
+ export declare function build(config: RslibConfig, options?: Pick<BuildOptions, 'lib' | 'watch'>): Promise<RsbuildInstance>;
@@ -1,5 +1,6 @@
1
- import { type RsbuildMode } from '@rsbuild/core';
1
+ import type { RsbuildMode } from '@rsbuild/core';
2
2
  export type CommonOptions = {
3
+ root?: string;
3
4
  config?: string;
4
5
  envMode?: string;
5
6
  lib?: string[];
@@ -8,8 +9,8 @@ export type BuildOptions = CommonOptions & {
8
9
  watch?: boolean;
9
10
  };
10
11
  export type InspectOptions = CommonOptions & {
11
- mode: RsbuildMode;
12
- output: string;
12
+ mode?: RsbuildMode;
13
+ output?: string;
13
14
  verbose?: boolean;
14
15
  };
15
16
  export declare function runCli(): void;
@@ -0,0 +1,3 @@
1
+ import type { RslibConfig } from '../types';
2
+ import type { CommonOptions } from './commands';
3
+ export declare function loadRslibConfig(options: CommonOptions): Promise<RslibConfig>;
@@ -0,0 +1,4 @@
1
+ import { type RsbuildInstance } from '@rsbuild/core';
2
+ import type { RslibConfig } from '../types/config';
3
+ import type { InspectOptions } from './commands';
4
+ export declare function inspect(config: RslibConfig, options?: Pick<InspectOptions, 'lib' | 'mode' | 'output' | 'verbose'>): Promise<RsbuildInstance>;
@@ -1,3 +1,3 @@
1
1
  import type { RsbuildInstance } from '@rsbuild/core';
2
- import type { RslibConfig } from './types';
2
+ import type { RslibConfig } from '../types';
3
3
  export declare function startMFDevServer(config: RslibConfig): Promise<RsbuildInstance | undefined>;
@@ -1,5 +1,5 @@
1
1
  import { type EnvironmentConfig, type RsbuildConfig } from '@rsbuild/core';
2
- import type { AutoExternal, BannerAndFooter, Format, LibConfig, PkgJson, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, RslibConfigSyncFn } from './types';
2
+ import type { AutoExternal, BannerAndFooter, LibConfig, PkgJson, RsbuildConfigWithLibInfo, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, RslibConfigSyncFn } from './types';
3
3
  /**
4
4
  * This function helps you to autocomplete configuration types.
5
5
  * It accepts a Rslib config object, or a function that returns a config.
@@ -23,9 +23,6 @@ export declare function composeBannerFooterConfig(banner: BannerAndFooter, foote
23
23
  export declare function composeDecoratorsConfig(compilerOptions?: Record<string, any>, version?: NonNullable<NonNullable<RsbuildConfig['source']>['decorators']>['version']): RsbuildConfig;
24
24
  export declare function createConstantRsbuildConfig(): Promise<RsbuildConfig>;
25
25
  export declare const composeModuleImportWarn: (request: string) => string;
26
- export declare function composeCreateRsbuildConfig(rslibConfig: RslibConfig, path?: string): Promise<{
27
- format: Format;
28
- config: RsbuildConfig;
29
- }[]>;
26
+ export declare function composeCreateRsbuildConfig(rslibConfig: RslibConfig): Promise<RsbuildConfigWithLibInfo[]>;
30
27
  export declare function composeRsbuildEnvironments(rslibConfig: RslibConfig): Promise<Record<string, EnvironmentConfig>>;
31
28
  export declare const pruneEnvironments: (environments: Record<string, EnvironmentConfig>, libs?: string[]) => Record<string, EnvironmentConfig>;
@@ -1,6 +1,10 @@
1
1
  export declare const DEFAULT_CONFIG_NAME = "rslib.config";
2
2
  export declare const DEFAULT_CONFIG_EXTENSIONS: readonly [".js", ".ts", ".mjs", ".mts", ".cjs", ".cts"];
3
3
  export declare const SWC_HELPERS = "@swc/helpers";
4
+ export declare const RSLIB_ENTRY_QUERY = "__rslib_entry__";
5
+ export declare const SHEBANG_PREFIX = "#!";
6
+ export declare const SHEBANG_REGEX: RegExp;
7
+ export declare const REACT_DIRECTIVE_REGEX: RegExp;
4
8
  export declare const JS_EXTENSIONS: string[];
5
9
  export declare const CSS_EXTENSIONS: string[];
6
10
  export declare const ENTRY_EXTENSIONS: string[];
@@ -1,11 +1,11 @@
1
- import type { Compiler, RspackPluginInstance } from '@rspack/core';
1
+ import type { Rspack } from '@rsbuild/core';
2
2
  type Options = {
3
3
  include: RegExp;
4
4
  };
5
- declare class RemoveCssExtractAssetPlugin implements RspackPluginInstance {
5
+ declare class RemoveCssExtractAssetPlugin implements Rspack.RspackPluginInstance {
6
6
  readonly name: string;
7
7
  options: Options;
8
8
  constructor(options: Options);
9
- apply(compiler: Compiler): void;
9
+ apply(compiler: Rspack.Compiler): void;
10
10
  }
11
11
  export { RemoveCssExtractAssetPlugin };
@@ -1,4 +1,4 @@
1
- import type { LoaderDefinition } from '@rspack/core';
1
+ import type { Rspack } from '@rsbuild/core';
2
2
  export interface CssExtractRspackLoaderOptions {
3
3
  emit?: boolean;
4
4
  esModule?: boolean;
@@ -6,6 +6,6 @@ export interface CssExtractRspackLoaderOptions {
6
6
  defaultExport?: boolean;
7
7
  rootDir?: string;
8
8
  }
9
- declare const loader: LoaderDefinition;
10
- export declare const pitch: LoaderDefinition['pitch'];
9
+ declare const loader: Rspack.LoaderDefinition;
10
+ export declare const pitch: Rspack.LoaderDefinition['pitch'];
11
11
  export default loader;
@@ -1,7 +1,9 @@
1
1
  export { prepareCli } from './cli/prepare';
2
2
  export { runCli } from './cli/commands';
3
+ export { build } from './cli/build';
4
+ export { inspect } from './cli/inspect';
5
+ export { startMFDevServer } from './cli/mf';
3
6
  export { defineConfig, loadConfig, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, } from './config';
4
- export { build } from './build';
5
7
  export { logger } from './utils/logger';
6
8
  export type * from './types';
7
9
  export declare const version: string;
@@ -0,0 +1,4 @@
1
+ import { type RsbuildConfig } from '@rsbuild/core';
2
+ export declare const composeEntryChunkConfig: ({ enabledImportMetaUrlShim, }: {
3
+ enabledImportMetaUrlShim: boolean;
4
+ }) => RsbuildConfig;
@@ -0,0 +1,3 @@
1
+ import type { Rspack } from '@rsbuild/core';
2
+ declare const loader: Rspack.LoaderDefinition;
3
+ export default loader;
@@ -1,3 +1,4 @@
1
1
  import { type RsbuildPlugin } from '@rsbuild/core';
2
+ export declare const importMetaUrlShim = "const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {\n return typeof document === 'undefined'\n ? new (require('url'.replace('', '')).URL)('file:' + __filename).href\n : (document.currentScript && document.currentScript.src) ||\n new URL('main.js', document.baseURI).href;\n})();\n";
2
3
  export declare const pluginCjsImportMetaUrlShim: () => RsbuildPlugin;
3
4
  export declare const pluginEsmRequireShim: () => RsbuildPlugin;
@@ -4,6 +4,11 @@ export type Format = 'esm' | 'cjs' | 'umd' | 'mf';
4
4
  export type FixedEcmaVersions = 'es5' | 'es6' | 'es2015' | 'es2016' | 'es2017' | 'es2018' | 'es2019' | 'es2020' | 'es2021' | 'es2022' | 'es2023';
5
5
  export type LatestEcmaVersions = 'es2024' | 'esnext';
6
6
  export type EcmaScriptVersion = FixedEcmaVersions | LatestEcmaVersions;
7
+ export type RsbuildConfigWithLibInfo = {
8
+ id?: string;
9
+ format: Format;
10
+ config: RsbuildConfig;
11
+ };
7
12
  export type RsbuildConfigOutputTarget = NonNullable<RsbuildConfig['output']>['target'];
8
13
  export type Syntax = EcmaScriptVersion | string[];
9
14
  export type Dts = (Pick<PluginDtsOptions, 'bundle' | 'distPath' | 'abortOnError' | 'build'> & {
@@ -34,56 +39,70 @@ export type Redirect = {
34
39
  style?: boolean;
35
40
  };
36
41
  export interface LibConfig extends RsbuildConfig {
42
+ /**
43
+ * The unique identifier of the library.
44
+ * @defaultValue `undefined`
45
+ * @see {@link https://lib.rsbuild.dev/config/lib/id}
46
+ */
47
+ id?: string;
37
48
  /**
38
49
  * Output format for the generated JavaScript files.
39
- * @default undefined
50
+ * @defaultValue `undefined`
51
+ * @see {@link https://lib.rsbuild.dev/config/lib/format}
40
52
  */
41
53
  format?: Format;
42
54
  /**
43
55
  * Whether to bundle the library.
44
- * @default true
56
+ * @defaultValue `true`
57
+ * @see {@link https://lib.rsbuild.dev/config/lib/bundle}
45
58
  */
46
59
  bundle?: boolean;
47
60
  /**
48
- * Whether to automatically set the file extension based on the `format` option in the JavaScript output files.
49
- * @default true
61
+ * Whether to automatically set the file extension based on {@link format} option in the JavaScript output files.
62
+ * @defaultValue `true`
63
+ * @see {@link https://lib.rsbuild.dev/config/lib/auto-extension}
50
64
  */
51
65
  autoExtension?: boolean;
52
66
  /**
53
67
  * Whether to automatically externalize dependencies of different dependency types and do not bundle them.
54
- * @default true
68
+ * @defaultValue `true`
69
+ * @see {@link https://lib.rsbuild.dev/config/lib/auto-external}
55
70
  */
56
71
  autoExternal?: AutoExternal;
57
72
  /**
58
- * Configure the redirect of the import paths, applicable when `bundle: false`.
59
- * @default {}
73
+ * Configure the redirect of the import paths, applicable {@link bundle} is set to `false`.
74
+ * @defaultValue `{}`
75
+ * @see {@link https://lib.rsbuild.dev/config/lib/redirect}
60
76
  */
61
77
  redirect?: Redirect;
62
78
  /**
63
79
  * Configure the syntax to which JavaScript and CSS will be downgraded.
64
- * Support ECMAScript version and browserslist query.
65
- * @default 'esnext'
80
+ * @defaultValue `'esnext'`
81
+ * @see {@link https://lib.rsbuild.dev/config/lib/syntax}
66
82
  */
67
83
  syntax?: Syntax;
68
84
  /**
69
85
  * Whether to import SWC helper functions from `@swc/helpers` instead of inlining them.
70
- * @default false
86
+ * @defaultValue `false`
87
+ * @see {@link https://lib.rsbuild.dev/config/lib/external-helpers}
71
88
  */
72
89
  externalHelpers?: boolean;
73
90
  /**
74
91
  * Inject content into the top of each JS, CSS or DTS file.
75
- * @default {}
92
+ * @defaultValue `{}`
93
+ * @see {@link https://lib.rsbuild.dev/config/lib/banner}
76
94
  */
77
95
  banner?: BannerAndFooter;
78
96
  /**
79
97
  * Inject content into the bottom of each JS, CSS or DTS file.
80
- * @default {}
98
+ * @defaultValue `{}`
99
+ * @see {@link https://lib.rsbuild.dev/config/lib/footer}
81
100
  */
82
101
  footer?: BannerAndFooter;
83
102
  /**
84
103
  * Configure the shims for CommonJS and ESM output.
85
104
  *
86
- * @default
105
+ * @defaultValue
87
106
  * ```js
88
107
  * const defaultShims = {
89
108
  * cjs: {
@@ -96,16 +115,19 @@ export interface LibConfig extends RsbuildConfig {
96
115
  * },
97
116
  * };
98
117
  * ```
118
+ * @see {@link https://lib.rsbuild.dev/config/lib/shims}
99
119
  */
100
120
  shims?: Shims;
101
121
  /**
102
122
  * Configure the generation of the TypeScript declaration files.
103
- * @default false
123
+ * @defaultValue `false`
124
+ * @see {@link https://lib.rsbuild.dev/config/lib/dts}
104
125
  */
105
126
  dts?: Dts;
106
127
  /**
107
128
  * The export name of the UMD bundle.
108
- * @default undefined
129
+ * @defaultValue `undefined`
130
+ * @see {@link https://lib.rsbuild.dev/config/lib/umd-name}
109
131
  */
110
132
  umdName?: string;
111
133
  }
@@ -6,3 +6,7 @@ export type PkgJson = {
6
6
  devDependencies?: Record<string, string>;
7
7
  optionalDependencies?: Record<string, string>;
8
8
  };
9
+ export type DeepRequired<T> = Required<{
10
+ [K in keyof T]: T[K] extends Required<T[K]> ? T[K] : DeepRequired<T[K]>;
11
+ }>;
12
+ export type ExcludesFalse = <T>(x: T | false | undefined | null) => x is T;
@@ -1,3 +1,4 @@
1
+ import type { RsbuildPlugins } from '@rsbuild/core';
1
2
  import color from 'picocolors';
2
3
  import type { LibConfig, PkgJson } from '../types';
3
4
  /**
@@ -6,11 +7,12 @@ import type { LibConfig, PkgJson } from '../types';
6
7
  */
7
8
  export declare const nodeBuiltInModules: Array<string | RegExp>;
8
9
  export declare function calcLongestCommonPath(absPaths: string[]): Promise<string | null>;
10
+ export declare function getAbsolutePath(base: string, filepath: string): string;
9
11
  export declare const readPackageJson: (rootPath: string) => undefined | PkgJson;
10
12
  export declare const isObject: (obj: unknown) => obj is Record<string, any>;
11
13
  export declare const isEmptyObject: (obj: object) => boolean;
12
14
  export declare function pick<T, U extends keyof T>(obj: T, keys: ReadonlyArray<U>): Pick<T, U>;
13
15
  export declare function omit<T extends object, U extends keyof T>(obj: T, keysObj: Record<U, boolean>): Omit<T, keyof U>;
14
- export declare function isPluginIncluded(config: LibConfig, pluginName: string): boolean;
16
+ export declare function isPluginIncluded(pluginName: string, plugins?: RsbuildPlugins): boolean;
15
17
  export declare function checkMFPlugin(config: LibConfig): boolean;
16
18
  export { color };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rslib/core",
3
- "version": "0.0.17",
3
+ "version": "0.1.0",
4
4
  "description": "The Rsbuild-based library development tool.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -32,19 +32,18 @@
32
32
  "compiled"
33
33
  ],
34
34
  "dependencies": {
35
- "@rsbuild/core": "~1.1.0",
35
+ "@rsbuild/core": "~1.1.4",
36
36
  "tinyglobby": "^0.2.10",
37
- "rsbuild-plugin-dts": "0.0.17"
37
+ "rsbuild-plugin-dts": "0.1.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@rspack/core": "1.0.8",
41
40
  "@types/fs-extra": "^11.0.4",
42
41
  "commander": "^12.1.0",
43
42
  "fs-extra": "^11.2.0",
44
43
  "memfs": "^4.14.0",
45
44
  "picocolors": "1.1.1",
46
45
  "prebundle": "1.2.5",
47
- "rslib": "npm:@rslib/core@0.0.16",
46
+ "rslib": "npm:@rslib/core@0.0.18",
48
47
  "rslog": "^1.2.3",
49
48
  "tsconfck": "3.1.4",
50
49
  "typescript": "^5.6.3",
@@ -1,4 +0,0 @@
1
- import { type RsbuildInstance } from '@rsbuild/core';
2
- import type { BuildOptions } from './cli/commands';
3
- import type { RslibConfig } from './types/config';
4
- export declare function build(config: RslibConfig, options?: BuildOptions): Promise<RsbuildInstance>;