@rsbuild/core 0.0.20 → 0.0.21

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.
@@ -22,11 +22,11 @@ __export(commands_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(commands_exports);
24
24
  var import_path = require("path");
25
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
25
+ var import_shared = require("@rsbuild/shared");
26
26
  var import_commander = require("commander");
27
27
  function setupProgram(rsbuild) {
28
28
  const pkgJson = (0, import_path.join)(__dirname, "../../package.json");
29
- const { version } = import_fs_extra.fs.readJSONSync(pkgJson);
29
+ const { version } = import_shared.fse.readJSONSync(pkgJson);
30
30
  import_commander.program.name("rsbuild").usage("<command> [options]").version(version);
31
31
  import_commander.program.command("dev").option(`--open`, "open the page in browser on startup").description("starting the dev server").action(async (options) => {
32
32
  await rsbuild.startDevServer({
@@ -33,10 +33,11 @@ __export(config_exports, {
33
33
  loadConfig: () => loadConfig
34
34
  });
35
35
  module.exports = __toCommonJS(config_exports);
36
+ var import_fs = __toESM(require("fs"));
36
37
  var import_jiti = __toESM(require("jiti"));
37
38
  var import_path = require("path");
38
39
  var import_shared = require("@rsbuild/shared");
39
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
40
+ var import_restart = require("../server/restart");
40
41
  const defineConfig = (config) => config;
41
42
  const resolveConfigPath = () => {
42
43
  const CONFIG_FILES = [
@@ -50,19 +51,35 @@ const resolveConfigPath = () => {
50
51
  const root = process.cwd();
51
52
  for (const file of CONFIG_FILES) {
52
53
  const configFile = (0, import_path.join)(root, file);
53
- if (import_fs_extra.fs.existsSync(configFile)) {
54
+ if (import_fs.default.existsSync(configFile)) {
54
55
  return configFile;
55
56
  }
56
57
  }
57
58
  return null;
58
59
  };
60
+ async function watchConfig(configFile) {
61
+ const chokidar = await Promise.resolve().then(() => __toESM(require("@rsbuild/shared/chokidar")));
62
+ const watcher = chokidar.watch(configFile, {});
63
+ const callback = async () => {
64
+ watcher.close();
65
+ await (0, import_restart.restartDevServer)({ filePath: configFile });
66
+ };
67
+ watcher.on("change", callback);
68
+ watcher.on("unlink", callback);
69
+ }
59
70
  async function loadConfig() {
60
71
  const configFile = resolveConfigPath();
61
72
  if (configFile) {
62
73
  const loadConfig2 = (0, import_jiti.default)(__filename, {
63
74
  esmResolve: true,
75
+ // disable require cache to support restart CLI and read the new config
76
+ requireCache: false,
64
77
  interopDefault: true
65
78
  });
79
+ const command = process.argv[2];
80
+ if (command === "dev") {
81
+ watchConfig(configFile);
82
+ }
66
83
  return loadConfig2(configFile);
67
84
  }
68
85
  return {};
@@ -1,6 +1,2 @@
1
- import { RsbuildPlugin } from '..';
2
1
  export { defineConfig } from './config';
3
- type RunCliOptions = {
4
- defaultPlugins?: RsbuildPlugin[];
5
- };
6
- export declare function runCli(options?: RunCliOptions): Promise<void>;
2
+ export { runCli } from './run';
package/dist/cli/index.js CHANGED
@@ -18,30 +18,12 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var cli_exports = {};
20
20
  __export(cli_exports, {
21
- defineConfig: () => import_config2.defineConfig,
22
- runCli: () => runCli
21
+ defineConfig: () => import_config.defineConfig,
22
+ runCli: () => import_run.runCli
23
23
  });
24
24
  module.exports = __toCommonJS(cli_exports);
25
- var import__ = require("..");
26
- var import_commands = require("./commands");
27
25
  var import_config = require("./config");
28
- var import_config2 = require("./config");
29
- async function runCli(options = {}) {
30
- var _a;
31
- const config = await (0, import_config.loadConfig)();
32
- const rsbuild = await (0, import__.createRsbuild)({
33
- rsbuildConfig: config,
34
- entry: ((_a = config.source) == null ? void 0 : _a.entries) || (0, import_config.getDefaultEntries)(),
35
- provider: config.provider
36
- });
37
- if (options.defaultPlugins) {
38
- rsbuild.addPlugins(options.defaultPlugins);
39
- }
40
- if (config.plugins) {
41
- rsbuild.addPlugins(config.plugins);
42
- }
43
- (0, import_commands.setupProgram)(rsbuild);
44
- }
26
+ var import_run = require("./run");
45
27
  // Annotate the CommonJS export names for ESM import in node:
46
28
  0 && (module.exports = {
47
29
  defineConfig,
@@ -0,0 +1,7 @@
1
+ import { RsbuildPlugin } from '..';
2
+ type RunCliOptions = {
3
+ isRestart?: boolean;
4
+ defaultPlugins?: RsbuildPlugin[];
5
+ };
6
+ export declare function runCli(options?: RunCliOptions): Promise<import("..").RsbuildInstance<any>>;
7
+ export {};
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var run_exports = {};
20
+ __export(run_exports, {
21
+ runCli: () => runCli
22
+ });
23
+ module.exports = __toCommonJS(run_exports);
24
+ var import__ = require("..");
25
+ var import_commands = require("./commands");
26
+ var import_config = require("./config");
27
+ async function runCli(options = {}) {
28
+ var _a;
29
+ const config = await (0, import_config.loadConfig)();
30
+ const rsbuild = await (0, import__.createRsbuild)({
31
+ rsbuildConfig: config,
32
+ entry: ((_a = config.source) == null ? void 0 : _a.entries) || (0, import_config.getDefaultEntries)(),
33
+ provider: config.provider
34
+ });
35
+ if (options.defaultPlugins) {
36
+ rsbuild.addPlugins(options.defaultPlugins);
37
+ }
38
+ if (config.plugins) {
39
+ rsbuild.addPlugins(config.plugins);
40
+ }
41
+ if (!options.isRestart) {
42
+ (0, import_commands.setupProgram)(rsbuild);
43
+ }
44
+ return rsbuild;
45
+ }
46
+ // Annotate the CommonJS export names for ESM import in node:
47
+ 0 && (module.exports = {
48
+ runCli
49
+ });
@@ -33,18 +33,18 @@ __export(cache_exports, {
33
33
  module.exports = __toCommonJS(cache_exports);
34
34
  var import_crypto = __toESM(require("crypto"));
35
35
  var import_path = require("path");
36
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
37
36
  var import_shared = require("@rsbuild/shared");
37
+ var import_shared2 = require("@rsbuild/shared");
38
38
  async function validateCache(cacheDirectory, buildDependencies) {
39
39
  const configFile = (0, import_path.join)(cacheDirectory, "buildDependencies.json");
40
- if (await (0, import_shared.isFileExists)(configFile)) {
41
- const prevBuildDependencies = await import_fs_extra.fs.readJSON(configFile);
40
+ if (await (0, import_shared2.isFileExists)(configFile)) {
41
+ const prevBuildDependencies = await import_shared.fse.readJSON(configFile);
42
42
  if (JSON.stringify(prevBuildDependencies) === JSON.stringify(buildDependencies)) {
43
43
  return;
44
44
  }
45
- await import_fs_extra.fs.remove(cacheDirectory);
45
+ await import_shared.fse.remove(cacheDirectory);
46
46
  }
47
- await import_fs_extra.fs.outputJSON(configFile, buildDependencies);
47
+ await import_shared.fse.outputJSON(configFile, buildDependencies);
48
48
  }
49
49
  function getDigestHash(digest) {
50
50
  const fsHash = import_crypto.default.createHash("md5");
@@ -61,7 +61,7 @@ async function getBuildDependencies(context) {
61
61
  const rootPackageJson = (0, import_path.join)(context.rootPath, "package.json");
62
62
  const browserslistConfig = (0, import_path.join)(context.rootPath, ".browserslistrc");
63
63
  const buildDependencies = {};
64
- if (await (0, import_shared.isFileExists)(rootPackageJson)) {
64
+ if (await (0, import_shared2.isFileExists)(rootPackageJson)) {
65
65
  buildDependencies.packageJson = [rootPackageJson];
66
66
  }
67
67
  if (context.configPath) {
@@ -70,14 +70,14 @@ async function getBuildDependencies(context) {
70
70
  if (context.tsconfigPath) {
71
71
  buildDependencies.tsconfig = [context.tsconfigPath];
72
72
  }
73
- if (await (0, import_shared.isFileExists)(browserslistConfig)) {
73
+ if (await (0, import_shared2.isFileExists)(browserslistConfig)) {
74
74
  buildDependencies.browserslistrc = [browserslistConfig];
75
75
  }
76
76
  const tailwindExts = ["ts", "js", "cjs", "mjs"];
77
77
  const configs = tailwindExts.map(
78
78
  (ext) => (0, import_path.join)(context.rootPath, `tailwind.config.${ext}`)
79
79
  );
80
- const tailwindConfig = (0, import_shared.findExists)(configs);
80
+ const tailwindConfig = (0, import_shared2.findExists)(configs);
81
81
  if (tailwindConfig) {
82
82
  buildDependencies.tailwindcss = [tailwindConfig];
83
83
  }
@@ -21,10 +21,10 @@ __export(cleanOutput_exports, {
21
21
  pluginCleanOutput: () => pluginCleanOutput
22
22
  });
23
23
  module.exports = __toCommonJS(cleanOutput_exports);
24
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
24
+ var import_shared = require("@rsbuild/shared");
25
25
  const emptyDir = async (dir) => {
26
- if (await import_fs_extra.fs.pathExists(dir)) {
27
- await import_fs_extra.fs.emptyDir(dir);
26
+ if (await import_shared.fse.pathExists(dir)) {
27
+ await import_shared.fse.emptyDir(dir);
28
28
  }
29
29
  };
30
30
  const pluginCleanOutput = () => ({
@@ -33,19 +33,18 @@ __export(fileSize_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(fileSize_exports);
35
35
  var import_path = __toESM(require("path"));
36
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
37
36
  var import_shared = require("@rsbuild/shared");
38
- var import_filesize = __toESM(require("filesize"));
37
+ var import_shared2 = require("@rsbuild/shared");
39
38
  var import_gzip_size = __toESM(require("gzip-size"));
40
39
  const filterAsset = (asset) => !/\.map$/.test(asset) && !/\.LICENSE\.txt$/.test(asset);
41
40
  const getAssetColor = (size) => {
42
41
  if (size > 300 * 1e3) {
43
- return import_shared.color.red;
42
+ return import_shared2.color.red;
44
43
  }
45
44
  if (size > 100 * 1e3) {
46
- return import_shared.color.yellow;
45
+ return import_shared2.color.yellow;
47
46
  }
48
- return import_shared.color.green;
47
+ return import_shared2.color.green;
49
48
  };
50
49
  async function printHeader(longestFileLength, longestLabelLength) {
51
50
  const longestLengths = [longestFileLength, longestLabelLength];
@@ -57,11 +56,15 @@ async function printHeader(longestFileLength, longestLabelLength) {
57
56
  }
58
57
  return `${prev + curLabel} `;
59
58
  }, " ");
60
- import_shared.logger.log(import_shared.color.bold(import_shared.color.blue(headerRow)));
59
+ import_shared2.logger.log(import_shared2.color.bold(import_shared2.color.blue(headerRow)));
61
60
  }
61
+ const calcFileSize = (len) => {
62
+ const val = len / 1e3;
63
+ return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
64
+ };
62
65
  async function printFileSizes(stats, distPath) {
63
66
  const formatAsset = (asset) => {
64
- const contents = import_fs_extra.fs.readFileSync(import_path.default.join(distPath, asset.name));
67
+ const contents = import_shared.fse.readFileSync(import_path.default.join(distPath, asset.name));
65
68
  const size = contents.length;
66
69
  const gzippedSize = import_gzip_size.default.sync(contents);
67
70
  return {
@@ -69,10 +72,8 @@ async function printFileSizes(stats, distPath) {
69
72
  folder: import_path.default.join(import_path.default.basename(distPath), import_path.default.dirname(asset.name)),
70
73
  name: import_path.default.basename(asset.name),
71
74
  gzippedSize,
72
- sizeLabel: (0, import_filesize.default)(size, { round: 1 }),
73
- gzipSizeLabel: getAssetColor(gzippedSize)(
74
- (0, import_filesize.default)(gzippedSize, { round: 1 })
75
- )
75
+ sizeLabel: calcFileSize(size),
76
+ gzipSizeLabel: getAssetColor(gzippedSize)(calcFileSize(gzippedSize))
76
77
  };
77
78
  };
78
79
  const multiStats = "stats" in stats ? stats.stats : [stats];
@@ -100,7 +101,7 @@ async function printFileSizes(stats, distPath) {
100
101
  const longestFileLength = Math.max(
101
102
  ...assets.map((a) => (a.folder + import_path.default.sep + a.name).length)
102
103
  );
103
- import_shared.logger.info(`Production file sizes:
104
+ import_shared2.logger.info(`Production file sizes:
104
105
  `);
105
106
  printHeader(longestFileLength, longestLabelLength);
106
107
  let totalSize = 0;
@@ -116,21 +117,20 @@ async function printFileSizes(stats, distPath) {
116
117
  const rightPadding = " ".repeat(longestLabelLength - sizeLength);
117
118
  sizeLabel += rightPadding;
118
119
  }
119
- let fileNameLabel = import_shared.color.dim(asset.folder + import_path.default.sep) + import_shared.color.cyan(asset.name);
120
+ let fileNameLabel = import_shared2.color.dim(asset.folder + import_path.default.sep) + import_shared2.color.cyan(asset.name);
120
121
  if (fileNameLength < longestFileLength) {
121
122
  const rightPadding = " ".repeat(longestFileLength - fileNameLength);
122
123
  fileNameLabel += rightPadding;
123
124
  }
124
- import_shared.logger.log(` ${fileNameLabel} ${sizeLabel} ${gzipSizeLabel}`);
125
+ import_shared2.logger.log(` ${fileNameLabel} ${sizeLabel} ${gzipSizeLabel}`);
125
126
  });
126
- const totalSizeLabel = `${import_shared.color.bold(import_shared.color.blue("Total size:"))} ${(0, import_filesize.default)(
127
- totalSize,
128
- { round: 1 }
129
- )}`;
130
- const gzippedSizeLabel = `${import_shared.color.bold(
131
- import_shared.color.blue("Gzipped size:")
132
- )} ${(0, import_filesize.default)(totalGzipSize, { round: 1 })}`;
133
- import_shared.logger.log(`
127
+ const totalSizeLabel = `${import_shared2.color.bold(
128
+ import_shared2.color.blue("Total size:")
129
+ )} ${calcFileSize(totalSize)}`;
130
+ const gzippedSizeLabel = `${import_shared2.color.bold(
131
+ import_shared2.color.blue("Gzipped size:")
132
+ )} ${calcFileSize(totalGzipSize)}`;
133
+ import_shared2.logger.log(`
134
134
  ${totalSizeLabel}
135
135
  ${gzippedSizeLabel}
136
136
  `);
@@ -144,8 +144,8 @@ const pluginFileSize = () => ({
144
144
  try {
145
145
  await printFileSizes(stats, api.context.distPath);
146
146
  } catch (err) {
147
- import_shared.logger.error("Failed to print file size.");
148
- import_shared.logger.error(err);
147
+ import_shared2.logger.error("Failed to print file size.");
148
+ import_shared2.logger.error(err);
149
149
  }
150
150
  }
151
151
  });
@@ -40,8 +40,6 @@ __export(html_exports, {
40
40
  module.exports = __toCommonJS(html_exports);
41
41
  var import_path = __toESM(require("path"));
42
42
  var import_shared = require("@rsbuild/shared");
43
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
44
- var import_lodash = __toESM(require("lodash"));
45
43
  var import_HtmlBasicPlugin = require("../rspack-plugins/HtmlBasicPlugin");
46
44
  function getTitle(entryName, config) {
47
45
  return (0, import_shared.mergeChainedOptions)({
@@ -133,11 +131,13 @@ const applyInjectTags = (api) => {
133
131
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID }) => {
134
132
  const config = api.getNormalizedConfig();
135
133
  const tags = (0, import_shared.castArray)(config.html.tags).filter(Boolean);
136
- const tagsByEntries = import_lodash.default.mapValues(
137
- config.html.tagsByEntries,
138
- (tags2) => (0, import_shared.castArray)(tags2).filter(Boolean)
134
+ const tagsByEntries = config.html.tagsByEntries || {};
135
+ Object.keys(tagsByEntries).forEach(
136
+ (key) => tagsByEntries[key] = (0, import_shared.castArray)(tagsByEntries[key]).filter(Boolean)
137
+ );
138
+ const shouldByEntries = Object.values(tagsByEntries).some(
139
+ (entry) => Array.isArray(entry) && entry.length > 0
139
140
  );
140
- const shouldByEntries = import_lodash.default.some(tagsByEntries, "length");
141
141
  if (!tags.length && !shouldByEntries) {
142
142
  return;
143
143
  }
@@ -163,7 +163,6 @@ const applyInjectTags = (api) => {
163
163
  const pluginHtml = () => ({
164
164
  name: "plugin-html",
165
165
  setup(api) {
166
- const routesInfo = [];
167
166
  api.modifyBundlerChain(
168
167
  async (chain, { HtmlPlugin, isProd, CHAIN_ID, target }) => {
169
168
  const config = api.getNormalizedConfig();
@@ -225,12 +224,6 @@ const pluginHtml = () => ({
225
224
  entryValue
226
225
  }
227
226
  });
228
- routesInfo.push({
229
- urlPath: index === 0 ? "/" : `/${entryName}`,
230
- entryName,
231
- entryPath: filename,
232
- isSPA: true
233
- });
234
227
  chain.plugin(`${CHAIN_ID.PLUGIN.HTML}-${entryName}`).use(HtmlPlugin, [finalOptions]);
235
228
  })
236
229
  );
@@ -261,17 +254,6 @@ const pluginHtml = () => ({
261
254
  }
262
255
  }
263
256
  );
264
- const emitRouteJson = async () => {
265
- const routeFilePath = import_path.default.join(api.context.distPath, import_shared.ROUTE_SPEC_FILE);
266
- if (!await (0, import_shared.isFileExists)(routeFilePath) && routesInfo.length) {
267
- await import_fs_extra.fs.outputFile(
268
- routeFilePath,
269
- JSON.stringify({ routes: routesInfo }, null, 2)
270
- );
271
- }
272
- };
273
- api.onBeforeBuild(emitRouteJson);
274
- api.onBeforeStartDevServer(emitRouteJson);
275
257
  applyInjectTags(api);
276
258
  }
277
259
  });
@@ -31,8 +31,8 @@ __export(rem_exports, {
31
31
  pluginRem: () => pluginRem
32
32
  });
33
33
  module.exports = __toCommonJS(rem_exports);
34
- var import_lodash = __toESM(require("lodash"));
35
34
  var import_shared = require("@rsbuild/shared");
35
+ var import_shared2 = require("@rsbuild/shared");
36
36
  const defaultOptions = {
37
37
  enableRuntime: true,
38
38
  rootFontSize: 50
@@ -65,7 +65,7 @@ const pluginRem = () => ({
65
65
  rootValue: userOptions.rootFontSize,
66
66
  unitPrecision: 5,
67
67
  propList: ["*"],
68
- ...import_lodash.default.cloneDeep(userOptions.pxtorem || {})
68
+ ...userOptions.pxtorem ? (0, import_shared2.cloneDeep)(userOptions.pxtorem) : {}
69
69
  });
70
70
  applyRules.forEach((name) => {
71
71
  chain.module.rules.has(name) && chain.module.rule(name).use(CHAIN_ID.USE.POSTCSS).tap((options = {}) => {
@@ -96,7 +96,7 @@ function pluginStartUrl() {
96
96
  name: "plugin-start-url",
97
97
  setup(api) {
98
98
  api.onAfterStartDevServer(async (params) => {
99
- const { port } = params;
99
+ const { port, routes } = params;
100
100
  const config = api.getNormalizedConfig();
101
101
  const { startUrl, beforeStartUrl } = config.dev;
102
102
  const { open, https } = api.context.devServer || {};
@@ -106,8 +106,6 @@ function pluginStartUrl() {
106
106
  }
107
107
  const urls = [];
108
108
  if (startUrl === true || !startUrl) {
109
- const { entry } = api.context;
110
- const routes = (0, import_shared.formatRoutes)(entry);
111
109
  const protocol = https ? "https" : "http";
112
110
  urls.push(
113
111
  (0, import_shared.normalizeUrl)(`${protocol}://localhost:${port}/${routes[0].route}`)
@@ -1,5 +1,6 @@
1
1
  import { OnExitFn, OnAfterBuildFn, OnBeforeBuildFn, OnDevCompileDoneFn, ModifyRsbuildConfigFn, OnAfterStartDevServerFn, OnBeforeStartDevServerFn, OnAfterCreateCompilerFn, OnBeforeCreateCompilerFn, ModifyBundlerChainFn, type RspackConfig, type ModifyRspackConfigFn } from '@rsbuild/shared';
2
2
  import type { RsbuildConfig } from '../types';
3
+ import type { Compiler, MultiCompiler } from '@rspack/core';
3
4
  export declare function initHooks(): {
4
5
  /** parameters are not bundler-related */
5
6
  onExitHook: import("@rsbuild/shared").AsyncHook<OnExitFn>;
@@ -11,7 +12,7 @@ export declare function initHooks(): {
11
12
  onBeforeBuildHook: import("@rsbuild/shared").AsyncHook<OnBeforeBuildFn<RspackConfig>>;
12
13
  modifyRspackConfigHook: import("@rsbuild/shared").AsyncHook<ModifyRspackConfigFn>;
13
14
  modifyRsbuildConfigHook: import("@rsbuild/shared").AsyncHook<ModifyRsbuildConfigFn<RsbuildConfig>>;
14
- onAfterCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnAfterCreateCompilerFn<import("@rspack/core/dist/Compiler").Compiler | import("@rspack/core").MultiCompiler>>;
15
+ onAfterCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnAfterCreateCompilerFn<Compiler | MultiCompiler>>;
15
16
  onBeforeCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnBeforeCreateCompilerFn<RspackConfig>>;
16
17
  modifyBundlerChainHook: import("@rsbuild/shared").AsyncHook<ModifyBundlerChainFn>;
17
18
  };
@@ -35,18 +35,18 @@ module.exports = __toCommonJS(rspack_profile_exports);
35
35
  var import_path = __toESM(require("path"));
36
36
  var import_core = require("@rspack/core");
37
37
  var import_inspector = __toESM(require("inspector"));
38
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
39
38
  var import_shared = require("@rsbuild/shared");
39
+ var import_shared2 = require("@rsbuild/shared");
40
40
  const stopProfiler = (output, profileSession) => {
41
41
  if (!profileSession) {
42
42
  return;
43
43
  }
44
44
  profileSession.post("Profiler.stop", (error, param) => {
45
45
  if (error) {
46
- import_shared.logger.error("Failed to generate JS CPU profile:", error);
46
+ import_shared2.logger.error("Failed to generate JS CPU profile:", error);
47
47
  return;
48
48
  }
49
- import_fs_extra.fs.writeFileSync(output, JSON.stringify(param.profile));
49
+ import_shared.fse.writeFileSync(output, JSON.stringify(param.profile));
50
50
  });
51
51
  };
52
52
  const pluginRspackProfile = () => ({
@@ -70,7 +70,7 @@ const pluginRspackProfile = () => ({
70
70
  const cpuProfilePath = import_path.default.join(profileDir, "jscpuprofile.json");
71
71
  const loggingFilePath = import_path.default.join(profileDir, "logging.json");
72
72
  const onStart = () => {
73
- import_fs_extra.fs.ensureDirSync(profileDir);
73
+ import_shared.fse.ensureDirSync(profileDir);
74
74
  if (enableProfileTrace) {
75
75
  (0, import_core.experimental_registerGlobalTrace)("trace", "chrome", traceFilePath);
76
76
  }
@@ -90,13 +90,13 @@ const pluginRspackProfile = () => ({
90
90
  logging: "verbose",
91
91
  loggingTrace: true
92
92
  });
93
- import_fs_extra.fs.writeFileSync(loggingFilePath, JSON.stringify(logging));
93
+ import_shared.fse.writeFileSync(loggingFilePath, JSON.stringify(logging));
94
94
  }
95
95
  });
96
96
  api.onExit(() => {
97
97
  enableProfileTrace && (0, import_core.experimental_cleanupGlobalTrace)();
98
98
  stopProfiler(cpuProfilePath, profileSession);
99
- import_shared.logger.info(`Saved Rspack profile file to ${profileDir}`);
99
+ import_shared2.logger.info(`Saved Rspack profile file to ${profileDir}`);
100
100
  });
101
101
  }
102
102
  });
@@ -33,7 +33,6 @@ __export(swc_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(swc_exports);
35
35
  var import_shared = require("@rsbuild/shared");
36
- var import_lodash = require("lodash");
37
36
  var path = __toESM(require("path"));
38
37
  const builtinSwcLoaderName = "builtin:swc-loader";
39
38
  async function getDefaultSwcConfig(config, rootPath, target) {
@@ -99,7 +98,7 @@ const pluginSwc = () => ({
99
98
  rule.use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(swcConfig);
100
99
  chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
101
100
  or: ["text/javascript", "application/javascript"]
102
- }).use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options((0, import_lodash.cloneDeep)(swcConfig));
101
+ }).use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options((0, import_shared.cloneDeep)(swcConfig));
103
102
  }
104
103
  );
105
104
  api.modifyRspackConfig(async (config) => {
@@ -80,8 +80,8 @@ function rspackProvider({
80
80
  options
81
81
  );
82
82
  },
83
- async preview() {
84
- return (0, import_server.startProdServer)(context, context.config);
83
+ async preview(options) {
84
+ return (0, import_server.startProdServer)(context, context.config, options);
85
85
  },
86
86
  async build(options) {
87
87
  const { build: buildImpl, rspackBuild } = await Promise.resolve().then(() => __toESM(require("./core/build")));
@@ -1,4 +1,4 @@
1
- import type { CssModuleLocalsConvention } from '@rsbuild/shared';
1
+ import { type CssModuleLocalsConvention } from '@rsbuild/shared';
2
2
  import type { AcceptedPlugin as PostCSSPlugin } from 'postcss';
3
3
  export type PostcssParsePluginOptions = {
4
4
  exportLocalsConvention: CssModuleLocalsConvention;
@@ -22,16 +22,16 @@ __export(postcss_icss_extract_plugin_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(postcss_icss_extract_plugin_exports);
24
24
  var import_icss_utils = require("@rsbuild/shared/icss-utils");
25
- var import_lodash = require("lodash");
25
+ var import_shared = require("@rsbuild/shared");
26
26
  const dashesCamelCase = (str) => str.replace(/-+(\w)/g, (_match, firstLetter) => firstLetter.toUpperCase());
27
27
  const getExportLocalsConvention = (name, exportLocalsConventionType) => {
28
28
  switch (exportLocalsConventionType) {
29
29
  case "camelCase": {
30
- const camelName = (0, import_lodash.camelCase)(name);
31
- return camelName === name ? [name] : [name, (0, import_lodash.camelCase)(name)];
30
+ const camelName = (0, import_shared.camelCase)(name);
31
+ return camelName === name ? [name] : [name, (0, import_shared.camelCase)(name)];
32
32
  }
33
33
  case "camelCaseOnly": {
34
- return [(0, import_lodash.camelCase)(name)];
34
+ return [(0, import_shared.camelCase)(name)];
35
35
  }
36
36
  case "dashes": {
37
37
  const dashesCamelName = dashesCamelCase(name);
@@ -23,10 +23,10 @@ __export(fs_exports, {
23
23
  module.exports = __toCommonJS(fs_exports);
24
24
  var import_path = require("path");
25
25
  var import_shared = require("@rsbuild/shared");
26
- var import_fs_extra = require("@rsbuild/shared/fs-extra");
26
+ var import_shared2 = require("@rsbuild/shared");
27
27
  const getCompiledPath = (packageName) => {
28
28
  const providerCompilerPath = (0, import_path.join)(__dirname, "../../compiled", packageName);
29
- if (import_fs_extra.fs.existsSync(providerCompilerPath)) {
29
+ if (import_shared2.fse.existsSync(providerCompilerPath)) {
30
30
  return providerCompilerPath;
31
31
  } else {
32
32
  return (0, import_shared.getSharedPkgCompiledPath)(packageName);
@@ -1,27 +1,4 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
- var import_strip_ansi = __toESM(require("strip-ansi"));
25
2
  var import_format_stats = require("@rsbuild/shared/format-stats");
26
3
  var import_createSocketUrl = require("./createSocketUrl");
27
4
  const hadRuntimeError = false;
@@ -74,7 +51,7 @@ function handleWarnings(warnings) {
74
51
  );
75
52
  break;
76
53
  }
77
- console.warn((0, import_strip_ansi.default)(formatted.warnings[i]));
54
+ console.warn(formatted.warnings[i]);
78
55
  }
79
56
  }
80
57
  }
@@ -93,7 +70,7 @@ function handleErrors(errors) {
93
70
  });
94
71
  if (typeof console !== "undefined" && typeof console.error === "function") {
95
72
  for (const error of formatted.errors) {
96
- console.error((0, import_strip_ansi.default)(error));
73
+ console.error(error);
97
74
  }
98
75
  }
99
76
  }
@@ -41,6 +41,7 @@ var import_connect = __toESM(require("connect"));
41
41
  var import_proxy = require("./proxy");
42
42
  var import_middlewares = require("./middlewares");
43
43
  var import_path = require("path");
44
+ var import_restart = require("./restart");
44
45
  class RsbuildDevServer {
45
46
  constructor(options) {
46
47
  this.middlewares = (0, import_connect.default)();
@@ -164,7 +165,7 @@ async function startDevServer(options, startDevCompile, {
164
165
  logger: customLogger,
165
166
  getPortSilently
166
167
  } = {}) {
167
- var _a, _b, _c;
168
+ var _a, _b, _c, _d, _e;
168
169
  if (!process.env.NODE_ENV) {
169
170
  process.env.NODE_ENV = "development";
170
171
  }
@@ -183,6 +184,10 @@ async function startDevServer(options, startDevCompile, {
183
184
  };
184
185
  const protocol = https ? "https" : "http";
185
186
  let urls = (0, import_shared.getAddressUrls)(protocol, port, (_a = rsbuildConfig.dev) == null ? void 0 : _a.host);
187
+ const routes = (0, import_shared.formatRoutes)(
188
+ options.context.entry,
189
+ (_c = (_b = rsbuildConfig.output) == null ? void 0 : _b.distPath) == null ? void 0 : _c.html
190
+ );
186
191
  if (printURLs) {
187
192
  if ((0, import_shared.isFunction)(printURLs)) {
188
193
  urls = printURLs(urls);
@@ -190,7 +195,7 @@ async function startDevServer(options, startDevCompile, {
190
195
  throw new Error("Please return an array in the `printURLs` function.");
191
196
  }
192
197
  }
193
- (0, import_shared.printServerURLs)(urls, options.context.entry, logger);
198
+ (0, import_shared.printServerURLs)(urls, routes, logger);
194
199
  }
195
200
  (0, import_shared.debug)("create dev server");
196
201
  const devMiddleware = await startDevCompile(options, compiler);
@@ -199,7 +204,7 @@ async function startDevServer(options, startDevCompile, {
199
204
  devMiddleware,
200
205
  dev: devServerConfig,
201
206
  output: {
202
- distPath: ((_c = (_b = rsbuildConfig.output) == null ? void 0 : _b.distPath) == null ? void 0 : _c.root) || import_shared.ROOT_DIST_DIR,
207
+ distPath: ((_e = (_d = rsbuildConfig.output) == null ? void 0 : _d.distPath) == null ? void 0 : _e.root) || import_shared.ROOT_DIST_DIR,
203
208
  assetPrefix: typeof devServerConfig.assetPrefix === "string" && !(0, import_shared.isURL)(devServerConfig.assetPrefix) ? devServerConfig.assetPrefix : ""
204
209
  }
205
210
  });
@@ -219,7 +224,11 @@ async function startDevServer(options, startDevCompile, {
219
224
  throw err;
220
225
  }
221
226
  (0, import_shared.debug)("listen dev server done");
222
- await options.context.hooks.onAfterStartDevServerHook.call({ port });
227
+ await options.context.hooks.onAfterStartDevServerHook.call({
228
+ port,
229
+ routes
230
+ });
231
+ (0, import_restart.registerCleaner)(() => server.close());
223
232
  resolve({
224
233
  port,
225
234
  urls: urls.map((item) => item.url),
@@ -3,7 +3,7 @@
3
3
  import type { ListenOptions } from 'net';
4
4
  import { Server } from 'http';
5
5
  import connect from 'connect';
6
- import { Context, RsbuildConfig, StartServerResult } from '@rsbuild/shared';
6
+ import { Context, RsbuildConfig, StartServerResult, PreviewServerOptions } from '@rsbuild/shared';
7
7
  type RsbuildProdServerOptions = {
8
8
  pwd: string;
9
9
  output: {
@@ -23,5 +23,7 @@ export declare class RsbuildProdServer {
23
23
  listen(options?: number | ListenOptions | undefined, listener?: () => void): void;
24
24
  close(): void;
25
25
  }
26
- export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig): Promise<StartServerResult>;
26
+ export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig, {
27
+ printURLs
28
+ }?: PreviewServerOptions): Promise<StartServerResult>;
27
29
  export {};
@@ -92,7 +92,7 @@ class RsbuildProdServer {
92
92
  this.app.close();
93
93
  }
94
94
  }
95
- async function startProdServer(context, rsbuildConfig) {
95
+ async function startProdServer(context, rsbuildConfig, { printURLs = true } = {}) {
96
96
  var _a, _b, _c, _d;
97
97
  if (!process.env.NODE_ENV) {
98
98
  process.env.NODE_ENV = "production";
@@ -114,8 +114,18 @@ async function startProdServer(context, rsbuildConfig) {
114
114
  port
115
115
  },
116
116
  () => {
117
+ var _a2, _b2;
117
118
  const urls = (0, import_shared.getAddressUrls)("http", port);
118
- (0, import_shared.printServerURLs)(urls, context.entry);
119
+ if (printURLs) {
120
+ const routes = (0, import_shared.formatRoutes)(
121
+ context.entry,
122
+ (_b2 = (_a2 = rsbuildConfig.output) == null ? void 0 : _a2.distPath) == null ? void 0 : _b2.html
123
+ );
124
+ (0, import_shared.printServerURLs)(
125
+ (0, import_shared.isFunction)(printURLs) ? printURLs(urls) : urls,
126
+ routes
127
+ );
128
+ }
119
129
  resolve({
120
130
  port,
121
131
  urls: urls.map((item) => item.url),
@@ -0,0 +1,11 @@
1
+ type Cleaner = () => Promise<unknown> | unknown;
2
+ /**
3
+ * Add a cleaner to handle side effects
4
+ */
5
+ export declare const registerCleaner: (cleaner: Cleaner) => void;
6
+ export declare const restartDevServer: ({
7
+ filePath
8
+ }: {
9
+ filePath: string;
10
+ }) => Promise<void>;
11
+ export {};
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var restart_exports = {};
30
+ __export(restart_exports, {
31
+ registerCleaner: () => registerCleaner,
32
+ restartDevServer: () => restartDevServer
33
+ });
34
+ module.exports = __toCommonJS(restart_exports);
35
+ var import_path = __toESM(require("path"));
36
+ var import_shared = require("@rsbuild/shared");
37
+ var import_run = require("../cli/run");
38
+ const cleaners = [];
39
+ const registerCleaner = (cleaner) => {
40
+ cleaners.push(cleaner);
41
+ };
42
+ const clearConsole = () => {
43
+ if (process.stdout.isTTY && !process.env.DEBUG) {
44
+ process.stdout.write("\x1B[H\x1B[2J");
45
+ }
46
+ };
47
+ const restartDevServer = async ({ filePath }) => {
48
+ clearConsole();
49
+ const filename = import_path.default.basename(filePath);
50
+ import_shared.logger.info(`Restart because ${import_shared.color.yellow(filename)} is changed.
51
+ `);
52
+ for (const cleaner of cleaners) {
53
+ await cleaner();
54
+ }
55
+ const rsbuild = await (0, import_run.runCli)({
56
+ isRestart: true
57
+ });
58
+ await rsbuild.startDevServer();
59
+ };
60
+ // Annotate the CommonJS export names for ESM import in node:
61
+ 0 && (module.exports = {
62
+ registerCleaner,
63
+ restartDevServer
64
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.0.20",
3
+ "version": "0.0.21",
4
4
  "description": "Unleash the power of Rspack with the out-of-the-box build tool.",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "bugs": {
@@ -47,28 +47,6 @@
47
47
  },
48
48
  "main": "./dist/index.js",
49
49
  "types": "./dist/index.d.ts",
50
- "typesVersions": {
51
- "*": {
52
- "cli": [
53
- "./dist/cli/index.d.ts"
54
- ],
55
- "server": [
56
- "./dist/server/index.d.ts"
57
- ],
58
- "hmr-client": [
59
- "./dist/server/dev-middleware/hmr-client/index.d.ts"
60
- ],
61
- "plugins/*": [
62
- "./dist/plugins/*.d.ts"
63
- ],
64
- "rspack-plugin-css": [
65
- "./dist/rspack-provider/plugins/css.d.ts"
66
- ],
67
- "rspack-provider": [
68
- "./dist/rspack-provider/index.d.ts"
69
- ]
70
- }
71
- },
72
50
  "bin": {
73
51
  "rsbuild": "./bin/rsbuild.js"
74
52
  },
@@ -84,26 +62,22 @@
84
62
  "connect-history-api-fallback": "^2.0.0",
85
63
  "commander": "^10.0.1",
86
64
  "core-js": "~3.32.2",
87
- "filesize": "^8.0.7",
88
65
  "gzip-size": "^6.0.0",
89
- "html-webpack-plugin": "npm:html-rspack-plugin@5.5.4",
66
+ "html-webpack-plugin": "npm:html-rspack-plugin@5.5.5",
90
67
  "http-compression": "1.0.6",
91
68
  "http-proxy-middleware": "^2.0.1",
92
69
  "jiti": "^1.20.0",
93
- "lodash": "^4.17.21",
94
70
  "open": "^8.4.0",
95
71
  "postcss": "8.4.31",
96
72
  "rslog": "^1.1.0",
97
73
  "semver": "^7.5.4",
98
74
  "sirv": "^2.0.3",
99
- "strip-ansi": "^6.0.1",
100
75
  "ws": "^8.2.0",
101
- "@rsbuild/shared": "0.0.20"
76
+ "@rsbuild/shared": "0.0.21"
102
77
  },
103
78
  "devDependencies": {
104
79
  "@types/connect": "3.4.35",
105
80
  "@types/connect-history-api-fallback": "^1.3.5",
106
- "@types/lodash": "^4.14.200",
107
81
  "@types/node": "^16",
108
82
  "@types/ws": "^8.2.0",
109
83
  "@types/semver": "^7.5.4",