@rsbuild/core 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/cli/commands.d.ts +5 -3
  2. package/dist/cli/commands.js +33 -11
  3. package/dist/cli/config.d.ts +13 -2
  4. package/dist/cli/config.js +29 -19
  5. package/dist/cli/prepare.js +1 -1
  6. package/dist/client/hmr.js +4 -4
  7. package/dist/createRsbuild.js +2 -0
  8. package/dist/index.d.ts +2 -2
  9. package/dist/index.js +3 -1
  10. package/dist/plugins/fileSize.js +43 -23
  11. package/dist/plugins/inlineChunk.js +1 -5
  12. package/dist/plugins/nodeAddons.js +1 -1
  13. package/dist/plugins/performance.js +3 -4
  14. package/dist/plugins/splitChunks.js +3 -5
  15. package/dist/plugins/startUrl.js +6 -4
  16. package/dist/rspack-provider/core/build.js +3 -3
  17. package/dist/rspack-provider/core/createContext.js +1 -1
  18. package/dist/rspack-provider/core/initConfigs.d.ts +4 -0
  19. package/dist/rspack-provider/core/initConfigs.js +16 -5
  20. package/dist/rspack-provider/core/initHooks.d.ts +4 -3
  21. package/dist/rspack-provider/core/initHooks.js +2 -0
  22. package/dist/rspack-provider/core/initPlugins.js +2 -0
  23. package/dist/rspack-provider/core/inspectConfig.d.ts +12 -1
  24. package/dist/rspack-provider/core/inspectConfig.js +6 -2
  25. package/dist/rspack-provider/core/rspackConfig.js +9 -4
  26. package/dist/rspack-provider/index.d.ts +2 -1
  27. package/dist/rspack-provider/index.js +5 -4
  28. package/dist/rspack-provider/plugins/css.js +1 -2
  29. package/dist/rspack-provider/plugins/less.js +1 -2
  30. package/dist/rspack-provider/plugins/progress.js +2 -5
  31. package/dist/rspack-provider/plugins/rspackProfile.js +1 -2
  32. package/dist/rspack-provider/plugins/sass.js +1 -2
  33. package/dist/rspack-provider/plugins/swc.js +5 -5
  34. package/dist/rspack-provider/provider.d.ts +2 -2
  35. package/dist/rspack-provider/provider.js +2 -0
  36. package/dist/rspack-provider/shared.js +1 -1
  37. package/dist/server/dev-middleware/index.js +5 -6
  38. package/dist/server/dev-middleware/socketServer.js +1 -2
  39. package/dist/server/devServer.d.ts +3 -4
  40. package/dist/server/devServer.js +6 -11
  41. package/dist/server/middlewares.js +1 -2
  42. package/dist/server/prodServer.d.ts +3 -3
  43. package/dist/server/prodServer.js +15 -17
  44. package/dist/server/proxy.js +1 -2
  45. package/dist/types.d.ts +2 -2
  46. package/package.json +3 -3
@@ -1,6 +1,9 @@
1
1
  import type { RsbuildMode } from '..';
2
2
  export type CommonOptions = {
3
3
  config?: string;
4
+ open?: boolean;
5
+ host?: string;
6
+ port?: number;
4
7
  };
5
8
  export type BuildOptions = CommonOptions & {
6
9
  watch?: boolean;
@@ -10,9 +13,8 @@ export type InspectOptions = CommonOptions & {
10
13
  output: string;
11
14
  verbose?: boolean;
12
15
  };
13
- export type DevOptions = CommonOptions & {
14
- open?: boolean;
15
- };
16
+ export type DevOptions = CommonOptions;
17
+ export type PreviewOptions = CommonOptions;
16
18
  export declare function init({
17
19
  cliOptions,
18
20
  isRestart
@@ -49,6 +49,18 @@ async function init({
49
49
  await (0, import_loadEnv.loadEnv)();
50
50
  const config = await (0, import_config.loadConfig)(commonOpts.config);
51
51
  const { createRsbuild } = await Promise.resolve().then(() => __toESM(require("../createRsbuild")));
52
+ if (commonOpts.open && !config.dev?.startUrl) {
53
+ config.dev || (config.dev = {});
54
+ config.dev.startUrl = true;
55
+ }
56
+ if (commonOpts.host) {
57
+ config.server || (config.server = {});
58
+ config.server.host = commonOpts.host;
59
+ }
60
+ if (commonOpts.port) {
61
+ config.server || (config.server = {});
62
+ config.server.port = commonOpts.port;
63
+ }
52
64
  return await createRsbuild({
53
65
  rsbuildConfig: config,
54
66
  provider: config.provider
@@ -62,16 +74,20 @@ async function init({
62
74
  }
63
75
  }
64
76
  function runCli() {
65
- import_commander.program.name("rsbuild").usage("<command> [options]").version("0.1.2");
66
- import_commander.program.command("dev").option(`--open`, "open the page in browser on startup").option(
77
+ import_commander.program.name("rsbuild").usage("<command> [options]").version("0.1.4");
78
+ import_commander.program.command("dev").option("--open", "open the page in browser on startup").option(
79
+ "--port <port>",
80
+ "specify a port number for Rsbuild Server to listen"
81
+ ).option(
82
+ "--host <host>",
83
+ "specify the host that the Rsbuild Server listens to"
84
+ ).option(
67
85
  "-c --config <config>",
68
86
  "specify the configuration file, can be a relative or absolute path"
69
87
  ).description("starting the dev server").action(async (options) => {
70
88
  try {
71
89
  const rsbuild = await init({ cliOptions: options });
72
- await (rsbuild == null ? void 0 : rsbuild.startDevServer({
73
- open: options.open
74
- }));
90
+ await rsbuild?.startDevServer();
75
91
  } catch (err) {
76
92
  import_shared.logger.error("Failed to start dev server.");
77
93
  import_shared.logger.error(err);
@@ -84,22 +100,28 @@ function runCli() {
84
100
  ).description("build the app for production").action(async (options) => {
85
101
  try {
86
102
  const rsbuild = await init({ cliOptions: options });
87
- await (rsbuild == null ? void 0 : rsbuild.build({
103
+ await rsbuild?.build({
88
104
  watch: options.watch
89
- }));
105
+ });
90
106
  } catch (err) {
91
107
  import_shared.logger.error("Failed to build.");
92
108
  import_shared.logger.error(err);
93
109
  process.exit(1);
94
110
  }
95
111
  });
96
- import_commander.program.command("preview").option(
112
+ import_commander.program.command("preview").option("--open", "open the page in browser on startup").option(
113
+ "--port <port>",
114
+ "specify a port number for Rsbuild Server to listen"
115
+ ).option(
116
+ "--host <host>",
117
+ "specify the host that the Rsbuild Server listens to"
118
+ ).option(
97
119
  "-c --config <config>",
98
120
  "specify the configuration file, can be a relative or absolute path"
99
121
  ).description("preview the production build locally").action(async (options) => {
100
122
  try {
101
123
  const rsbuild = await init({ cliOptions: options });
102
- await (rsbuild == null ? void 0 : rsbuild.preview());
124
+ await rsbuild?.preview();
103
125
  } catch (err) {
104
126
  import_shared.logger.error("Failed to start preview server.");
105
127
  import_shared.logger.error(err);
@@ -112,12 +134,12 @@ function runCli() {
112
134
  ).action(async (options) => {
113
135
  try {
114
136
  const rsbuild = await init({ cliOptions: options });
115
- await (rsbuild == null ? void 0 : rsbuild.inspectConfig({
137
+ await rsbuild?.inspectConfig({
116
138
  env: options.env,
117
139
  verbose: options.verbose,
118
140
  outputPath: (0, import_path.join)(rsbuild.context.distPath, options.output),
119
141
  writeToDisk: true
120
- }));
142
+ });
121
143
  } catch (err) {
122
144
  import_shared.logger.error("Failed to inspect config.");
123
145
  import_shared.logger.error(err);
@@ -5,5 +5,16 @@ export type RsbuildConfig = BaseRsbuildConfig & {
5
5
  */
6
6
  provider?: any;
7
7
  };
8
- export declare const defineConfig: (config: RsbuildConfig) => RsbuildConfig;
9
- export declare function loadConfig(customConfig?: string): Promise<ReturnType<typeof defineConfig>>;
8
+ export type ConfigParams = {
9
+ env: string;
10
+ command: string;
11
+ };
12
+ export type RsbuildConfigFn = (env: ConfigParams) => RsbuildConfig | Promise<RsbuildConfig>;
13
+ export type RsbuildConfigExport = RsbuildConfig | RsbuildConfigFn;
14
+ /**
15
+ * This function helps you to autocomplete configuration types.
16
+ * It accepts a Rsbuild config object, or a function that returns a config.
17
+ */
18
+ export declare function defineConfig(config: RsbuildConfig): RsbuildConfig;
19
+ export declare function defineConfig(config: RsbuildConfigFn): RsbuildConfigFn;
20
+ export declare function loadConfig(customConfig?: string): Promise<RsbuildConfig>;
@@ -36,7 +36,9 @@ var import_fs = __toESM(require("fs"));
36
36
  var import_path = require("path");
37
37
  var import_shared = require("@rsbuild/shared");
38
38
  var import_restart = require("../server/restart");
39
- const defineConfig = (config) => config;
39
+ function defineConfig(config) {
40
+ return config;
41
+ }
40
42
  const resolveConfigPath = (customConfig) => {
41
43
  const root = process.cwd();
42
44
  if (customConfig) {
@@ -82,26 +84,34 @@ async function watchConfig(configFile) {
82
84
  }
83
85
  async function loadConfig(customConfig) {
84
86
  const configFile = resolveConfigPath(customConfig);
85
- if (configFile) {
86
- try {
87
- const { default: jiti } = await Promise.resolve().then(() => __toESM(require("../../compiled/jiti")));
88
- const loadConfig2 = jiti(__filename, {
89
- esmResolve: true,
90
- // disable require cache to support restart CLI and read the new config
91
- requireCache: false,
92
- interopDefault: true
93
- });
94
- const command = process.argv[2];
95
- if (command === "dev") {
96
- watchConfig(configFile);
97
- }
98
- return loadConfig2(configFile);
99
- } catch (err) {
100
- import_shared.logger.error(`Failed to load file: ${import_shared.color.dim(configFile)}`);
101
- throw err;
87
+ if (!configFile) {
88
+ return {};
89
+ }
90
+ try {
91
+ const { default: jiti } = await Promise.resolve().then(() => __toESM(require("../../compiled/jiti")));
92
+ const loadConfig2 = jiti(__filename, {
93
+ esmResolve: true,
94
+ // disable require cache to support restart CLI and read the new config
95
+ requireCache: false,
96
+ interopDefault: true
97
+ });
98
+ const command = process.argv[2];
99
+ if (command === "dev") {
100
+ watchConfig(configFile);
101
+ }
102
+ const configExport = loadConfig2(configFile);
103
+ if (typeof configExport === "function") {
104
+ const params = {
105
+ env: process.env.NODE_ENV,
106
+ command
107
+ };
108
+ return await configExport(params) || {};
102
109
  }
110
+ return configExport;
111
+ } catch (err) {
112
+ import_shared.logger.error(`Failed to load file: ${import_shared.color.dim(configFile)}`);
113
+ throw err;
103
114
  }
104
- return {};
105
115
  }
106
116
  // Annotate the CommonJS export names for ESM import in node:
107
117
  0 && (module.exports = {
@@ -34,7 +34,7 @@ function prepareCli() {
34
34
  if (!npm_execpath || npm_execpath.includes("npx-cli.js")) {
35
35
  console.log();
36
36
  }
37
- import_rslog.logger.greet(` ${`Rsbuild v${"0.1.2"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.1.4"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
@@ -198,15 +198,15 @@ var require_formatStats = __commonJS({
198
198
  return message.trim();
199
199
  }
200
200
  function formatStatsMessages2(json) {
201
- var _a, _b, _c;
202
- var formattedErrors = (_a = json == null ? void 0 : json.errors) == null ? void 0 : _a.map(formatMessage);
203
- var formattedWarnings = (_b = json == null ? void 0 : json.warnings) == null ? void 0 : _b.map(formatMessage);
201
+ var _json_errors, _json_warnings, _result_errors;
202
+ var formattedErrors = json === null || json === void 0 ? void 0 : (_json_errors = json.errors) === null || _json_errors === void 0 ? void 0 : _json_errors.map(formatMessage);
203
+ var formattedWarnings = json === null || json === void 0 ? void 0 : (_json_warnings = json.warnings) === null || _json_warnings === void 0 ? void 0 : _json_warnings.map(formatMessage);
204
204
  var result = {
205
205
  errors: formattedErrors || [],
206
206
  warnings: formattedWarnings || [],
207
207
  errorTips: []
208
208
  };
209
- if ((_c = result.errors) == null ? void 0 : _c.some(isLikelyASyntaxError)) {
209
+ if ((_result_errors = result.errors) === null || _result_errors === void 0 ? void 0 : _result_errors.some(isLikelyASyntaxError)) {
210
210
  result.errors = result.errors.filter(isLikelyASyntaxError);
211
211
  }
212
212
  if (result.errors.length > 1) {
@@ -72,9 +72,11 @@ async function createRsbuild(options) {
72
72
  "onBeforeBuild",
73
73
  "onBeforeCreateCompiler",
74
74
  "onBeforeStartDevServer",
75
+ "onBeforeStartProdServer",
75
76
  "onAfterBuild",
76
77
  "onAfterCreateCompiler",
77
78
  "onAfterStartDevServer",
79
+ "onAfterStartProdServer",
78
80
  "onDevCompileDone",
79
81
  "onExit",
80
82
  "getHTMLPaths",
package/dist/index.d.ts CHANGED
@@ -3,8 +3,8 @@
3
3
  * the public API of @rsbuild/core.
4
4
  */
5
5
  export { createRsbuild } from './createRsbuild';
6
- export { mergeRsbuildConfig } from '@rsbuild/shared';
7
6
  export { defineConfig } from './cli/config';
7
+ export { logger, mergeRsbuildConfig } from '@rsbuild/shared';
8
8
  export type { Rspack } from './rspack-provider';
9
9
  export type { RsbuildConfig, NormalizedConfig, RsbuildPlugin, RsbuildPluginAPI } from './types';
10
- export type { Context as RsbuildContext, RsbuildMode, RsbuildEntry, RsbuildTarget, RsbuildInstance, CreateRsbuildOptions, InspectConfigOptions, OnExitFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterStartDevServerFn, OnBeforeBuildFn, OnBeforeStartDevServerFn, OnBeforeCreateCompilerFn, OnDevCompileDoneFn, ModifyRsbuildConfigFn } from '@rsbuild/shared';
10
+ export type { Context as RsbuildContext, RsbuildMode, RsbuildEntry, RsbuildTarget, RsbuildInstance, CreateRsbuildOptions, InspectConfigOptions, OnExitFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnBeforeCreateCompilerFn, OnDevCompileDoneFn, ModifyRsbuildConfigFn } from '@rsbuild/shared';
package/dist/index.js CHANGED
@@ -20,15 +20,17 @@ var src_exports = {};
20
20
  __export(src_exports, {
21
21
  createRsbuild: () => import_createRsbuild.createRsbuild,
22
22
  defineConfig: () => import_config.defineConfig,
23
+ logger: () => import_shared.logger,
23
24
  mergeRsbuildConfig: () => import_shared.mergeRsbuildConfig
24
25
  });
25
26
  module.exports = __toCommonJS(src_exports);
26
27
  var import_createRsbuild = require("./createRsbuild");
27
- var import_shared = require("@rsbuild/shared");
28
28
  var import_config = require("./cli/config");
29
+ var import_shared = require("@rsbuild/shared");
29
30
  // Annotate the CommonJS export names for ESM import in node:
30
31
  0 && (module.exports = {
31
32
  createRsbuild,
32
33
  defineConfig,
34
+ logger,
33
35
  mergeRsbuildConfig
34
36
  });
@@ -61,7 +61,10 @@ const calcFileSize = (len) => {
61
61
  const val = len / 1e3;
62
62
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
63
63
  };
64
- async function printFileSizes(stats, distPath) {
64
+ async function printFileSizes(config, stats, distPath) {
65
+ if (config.detail === false && config.total === false) {
66
+ return;
67
+ }
65
68
  const { default: gzipSize } = await Promise.resolve().then(() => __toESM(require("@rsbuild/shared/gzip-size")));
66
69
  const formatAsset = (asset) => {
67
70
  const fileName = asset.name.split("?")[0];
@@ -98,13 +101,15 @@ async function printFileSizes(stats, distPath) {
98
101
  return;
99
102
  }
100
103
  assets.sort((a, b) => b.size - a.size);
104
+ import_shared2.logger.info(`Production file sizes:
105
+ `);
101
106
  const longestLabelLength = Math.max(...assets.map((a) => a.sizeLabel.length));
102
107
  const longestFileLength = Math.max(
103
108
  ...assets.map((a) => (a.folder + import_path.default.sep + a.name).length)
104
109
  );
105
- import_shared2.logger.info(`Production file sizes:
106
- `);
107
- printHeader(longestFileLength, longestLabelLength);
110
+ if (config.detail !== false) {
111
+ printHeader(longestFileLength, longestLabelLength);
112
+ }
108
113
  let totalSize = 0;
109
114
  let totalGzipSize = 0;
110
115
  assets.forEach((asset) => {
@@ -114,36 +119,51 @@ async function printFileSizes(stats, distPath) {
114
119
  const sizeLength = sizeLabel.length;
115
120
  totalSize += asset.size;
116
121
  totalGzipSize += asset.gzippedSize;
117
- if (sizeLength < longestLabelLength) {
118
- const rightPadding = " ".repeat(longestLabelLength - sizeLength);
119
- sizeLabel += rightPadding;
120
- }
121
- let fileNameLabel = import_shared2.color.dim(asset.folder + import_path.default.sep) + import_shared2.color.cyan(asset.name);
122
- if (fileNameLength < longestFileLength) {
123
- const rightPadding = " ".repeat(longestFileLength - fileNameLength);
124
- fileNameLabel += rightPadding;
122
+ if (config.detail !== false) {
123
+ if (sizeLength < longestLabelLength) {
124
+ const rightPadding = " ".repeat(longestLabelLength - sizeLength);
125
+ sizeLabel += rightPadding;
126
+ }
127
+ let fileNameLabel = import_shared2.color.dim(asset.folder + import_path.default.sep) + import_shared2.color.cyan(asset.name);
128
+ if (fileNameLength < longestFileLength) {
129
+ const rightPadding = " ".repeat(longestFileLength - fileNameLength);
130
+ fileNameLabel += rightPadding;
131
+ }
132
+ import_shared2.logger.log(` ${fileNameLabel} ${sizeLabel} ${gzipSizeLabel}`);
125
133
  }
126
- import_shared2.logger.log(` ${fileNameLabel} ${sizeLabel} ${gzipSizeLabel}`);
127
134
  });
128
- const totalSizeLabel = `${import_shared2.color.bold(
129
- import_shared2.color.blue("Total size:")
130
- )} ${calcFileSize(totalSize)}`;
131
- const gzippedSizeLabel = `${import_shared2.color.bold(
132
- import_shared2.color.blue("Gzipped size:")
133
- )} ${calcFileSize(totalGzipSize)}`;
134
- import_shared2.logger.log(`
135
+ if (config.total !== false) {
136
+ const totalSizeLabel = `${import_shared2.color.bold(
137
+ import_shared2.color.blue("Total size:")
138
+ )} ${calcFileSize(totalSize)}`;
139
+ const gzippedSizeLabel = `${import_shared2.color.bold(
140
+ import_shared2.color.blue("Gzipped size:")
141
+ )} ${calcFileSize(totalGzipSize)}`;
142
+ import_shared2.logger.log(`
135
143
  ${totalSizeLabel}
136
144
  ${gzippedSizeLabel}
137
145
  `);
146
+ }
138
147
  }
139
148
  const pluginFileSize = () => ({
140
149
  name: "rsbuild:file-size",
141
150
  setup(api) {
142
151
  api.onAfterBuild(async ({ stats }) => {
143
- const config = api.getNormalizedConfig();
144
- if (config.performance.printFileSize && stats) {
152
+ const { printFileSize } = api.getNormalizedConfig().performance;
153
+ if (printFileSize === false) {
154
+ return;
155
+ }
156
+ const printFileSizeConfig = typeof printFileSize === "boolean" ? {
157
+ total: true,
158
+ detail: true
159
+ } : printFileSize;
160
+ if (stats) {
145
161
  try {
146
- await printFileSizes(stats, api.context.distPath);
162
+ await printFileSizes(
163
+ printFileSizeConfig,
164
+ stats,
165
+ api.context.distPath
166
+ );
147
167
  } catch (err) {
148
168
  import_shared2.logger.warn("Failed to print file size.");
149
169
  import_shared2.logger.warn(err);
@@ -42,11 +42,7 @@ const pluginInlineChunk = () => ({
42
42
  return;
43
43
  }
44
44
  const { InlineChunkHtmlPlugin } = await Promise.resolve().then(() => __toESM(require("@rsbuild/shared")));
45
- const {
46
- inlineStyles,
47
- // todo: not support inlineScripts in Rspack yet, which will take unknown build error
48
- inlineScripts
49
- } = config.output;
45
+ const { inlineStyles, inlineScripts } = config.output;
50
46
  const scriptTests = [];
51
47
  const styleTests = [];
52
48
  if (inlineScripts) {
@@ -46,7 +46,7 @@ const pluginNodeAddons = () => ({
46
46
  const getFilename = (resource, pkgName2) => {
47
47
  const reg = new RegExp(`node_modules/${pkgName2}/(.+)`);
48
48
  const match = resource.match(reg);
49
- const filename = match == null ? void 0 : match[1];
49
+ const filename = match?.[1];
50
50
  if (!filename) {
51
51
  return "[name].[ext]";
52
52
  }
@@ -35,10 +35,9 @@ const pluginPerformance = () => ({
35
35
  name: "rsbuild:performance",
36
36
  setup(api) {
37
37
  api.modifyRsbuildConfig((rsbuildConfig) => {
38
- var _a, _b, _c;
39
- if ((_a = rsbuildConfig.performance) == null ? void 0 : _a.profile) {
40
- if (!((_b = rsbuildConfig.performance) == null ? void 0 : _b.bundleAnalyze)) {
41
- (_c = rsbuildConfig.performance) != null ? _c : rsbuildConfig.performance = {};
38
+ if (rsbuildConfig.performance?.profile) {
39
+ if (!rsbuildConfig.performance?.bundleAnalyze) {
40
+ rsbuildConfig.performance ?? (rsbuildConfig.performance = {});
42
41
  rsbuildConfig.performance.bundleAnalyze = {
43
42
  analyzerMode: "disabled",
44
43
  generateStatsFile: true
@@ -109,13 +109,12 @@ function splitByModule(ctx) {
109
109
  };
110
110
  }
111
111
  function splitBySize(ctx) {
112
- var _a, _b;
113
112
  const { override, userDefinedCacheGroups, defaultConfig, rsbuildConfig } = ctx;
114
113
  (0, import_assert.default)(rsbuildConfig.strategy === "split-by-size");
115
114
  return {
116
115
  ...defaultConfig,
117
- minSize: (_a = rsbuildConfig.minSize) != null ? _a : 0,
118
- maxSize: (_b = rsbuildConfig.maxSize) != null ? _b : Infinity,
116
+ minSize: rsbuildConfig.minSize ?? 0,
117
+ maxSize: rsbuildConfig.maxSize ?? Infinity,
119
118
  ...override,
120
119
  cacheGroups: {
121
120
  ...defaultConfig.cacheGroups,
@@ -176,7 +175,6 @@ function pluginSplitChunks() {
176
175
  setup(api) {
177
176
  api.modifyBundlerChain(
178
177
  async (chain, { isServer, isWebWorker, isServiceWorker }) => {
179
- var _a;
180
178
  if (isServer || isWebWorker || isServiceWorker) {
181
179
  chain.optimization.splitChunks(false);
182
180
  if (isWebWorker || isServiceWorker) {
@@ -206,7 +204,7 @@ function pluginSplitChunks() {
206
204
  }
207
205
  const override = chunkSplit.strategy === "custom" ? (
208
206
  // `chunkSplit.splitChunks` compat for Eden
209
- (_a = chunkSplit.splitChunks) != null ? _a : chunkSplit.override
207
+ chunkSplit.splitChunks ?? chunkSplit.override
210
208
  ) : chunkSplit.override;
211
209
  const splitChunksOptions = await SPLIT_STRATEGY_DISPATCHER[chunkSplit.strategy]({
212
210
  defaultConfig,
@@ -95,12 +95,12 @@ function pluginStartUrl() {
95
95
  return {
96
96
  name: "rsbuild:start-url",
97
97
  setup(api) {
98
- api.onAfterStartDevServer(async (params) => {
98
+ const onStartServer = async (params) => {
99
99
  const { port, routes } = params;
100
100
  const config = api.getNormalizedConfig();
101
101
  const { startUrl, beforeStartUrl } = config.dev;
102
- const { open, https } = api.context.devServer || {};
103
- const shouldOpen = Boolean(startUrl) || open;
102
+ const { https } = api.context.devServer || {};
103
+ const shouldOpen = Boolean(startUrl);
104
104
  if (!shouldOpen) {
105
105
  return;
106
106
  }
@@ -136,7 +136,9 @@ function pluginStartUrl() {
136
136
  } else {
137
137
  openUrls();
138
138
  }
139
- });
139
+ };
140
+ api.onAfterStartDevServer(onStartServer);
141
+ api.onAfterStartProdServer(onStartServer);
140
142
  }
141
143
  };
142
144
  }
@@ -28,7 +28,7 @@ var import_shared = require("@rsbuild/shared");
28
28
  const rspackBuild = async (compiler) => {
29
29
  return new Promise((resolve, reject) => {
30
30
  compiler.run((err, stats) => {
31
- if (err || (stats == null ? void 0 : stats.hasErrors())) {
31
+ if (err || stats?.hasErrors()) {
32
32
  const buildError = err || new Error("Rspack build failed!");
33
33
  reject(buildError);
34
34
  } else {
@@ -66,9 +66,9 @@ const build = async (initOptions, { mode = "production", watch, compiler: custom
66
66
  }
67
67
  });
68
68
  } else {
69
- const executeResult = await (executer == null ? void 0 : executer(compiler));
69
+ const executeResult = await executer?.(compiler);
70
70
  await context.hooks.onAfterBuildHook.call({
71
- stats: executeResult == null ? void 0 : executeResult.stats
71
+ stats: executeResult?.stats
72
72
  });
73
73
  }
74
74
  };
@@ -64,7 +64,7 @@ function createContextByConfig(options, bundlerType, sourceConfig = {}, outputCo
64
64
  entry: sourceConfig.entry || // TODO: remove sourceConfig.entries in v0.2.0
65
65
  // compat with previous config
66
66
  sourceConfig.entries || getDefaultEntry(rootPath),
67
- version: "0.1.2",
67
+ version: "0.1.4",
68
68
  target,
69
69
  rootPath,
70
70
  distPath,
@@ -5,6 +5,10 @@ export type InitConfigsOptions = {
5
5
  pluginStore: PluginStore;
6
6
  rsbuildOptions: Required<CreateRsbuildOptions>;
7
7
  };
8
+ export declare function initRsbuildConfig({
9
+ context,
10
+ pluginStore
11
+ }: Pick<InitConfigsOptions, 'context' | 'pluginStore'>): Promise<void>;
8
12
  export declare function initConfigs({
9
13
  context,
10
14
  pluginStore,
@@ -18,7 +18,8 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var initConfigs_exports = {};
20
20
  __export(initConfigs_exports, {
21
- initConfigs: () => initConfigs
21
+ initConfigs: () => initConfigs,
22
+ initRsbuildConfig: () => initRsbuildConfig
22
23
  });
23
24
  module.exports = __toCommonJS(initConfigs_exports);
24
25
  var import_shared = require("@rsbuild/shared");
@@ -35,11 +36,13 @@ async function modifyRsbuildConfig(context) {
35
36
  context.config = modified;
36
37
  (0, import_shared.debug)("modify Rsbuild config done");
37
38
  }
38
- async function initConfigs({
39
+ async function initRsbuildConfig({
39
40
  context,
40
- pluginStore,
41
- rsbuildOptions
41
+ pluginStore
42
42
  }) {
43
+ if (context.normalizedConfig) {
44
+ return;
45
+ }
43
46
  await (0, import_shared.initPlugins)({
44
47
  pluginAPI: context.pluginAPI,
45
48
  pluginStore
@@ -47,6 +50,13 @@ async function initConfigs({
47
50
  await modifyRsbuildConfig(context);
48
51
  context.normalizedConfig = (0, import_config.normalizeConfig)(context.config);
49
52
  (0, import_createContext.updateContextByNormalizedConfig)(context, context.normalizedConfig);
53
+ }
54
+ async function initConfigs({
55
+ context,
56
+ pluginStore,
57
+ rsbuildOptions
58
+ }) {
59
+ await initRsbuildConfig({ context, pluginStore });
50
60
  const targets = (0, import_shared.castArray)(rsbuildOptions.target);
51
61
  const rspackConfigs = await Promise.all(
52
62
  targets.map((target) => (0, import_rspackConfig.generateRspackConfig)({ target, context }))
@@ -74,5 +84,6 @@ async function initConfigs({
74
84
  }
75
85
  // Annotate the CommonJS export names for ESM import in node:
76
86
  0 && (module.exports = {
77
- initConfigs
87
+ initConfigs,
88
+ initRsbuildConfig
78
89
  });
@@ -1,18 +1,19 @@
1
- import { type OnExitFn, type OnAfterBuildFn, type OnBeforeBuildFn, type OnDevCompileDoneFn, type ModifyRsbuildConfigFn, type OnAfterStartDevServerFn, type OnBeforeStartDevServerFn, type OnAfterCreateCompilerFn, type OnBeforeCreateCompilerFn, type ModifyBundlerChainFn, type RspackConfig, type ModifyRspackConfigFn } from '@rsbuild/shared';
1
+ import { type OnExitFn, type OnAfterBuildFn, type OnBeforeBuildFn, type OnDevCompileDoneFn, type ModifyRsbuildConfigFn, type OnAfterStartDevServerFn, type OnBeforeStartDevServerFn, type OnAfterStartProdServerFn, type OnBeforeStartProdServerFn, type OnAfterCreateCompilerFn, type OnBeforeCreateCompilerFn, type ModifyBundlerChainFn, type RspackConfig, type ModifyRspackConfigFn } from '@rsbuild/shared';
2
2
  import type { RsbuildConfig } from '../../types';
3
- import type { Compiler, MultiCompiler } from '@rspack/core';
4
3
  export declare function initHooks(): {
5
4
  /** parameters are not bundler-related */
6
5
  onExitHook: import("@rsbuild/shared").AsyncHook<OnExitFn>;
7
6
  onDevCompileDoneHook: import("@rsbuild/shared").AsyncHook<OnDevCompileDoneFn>;
8
7
  onAfterStartDevServerHook: import("@rsbuild/shared").AsyncHook<OnAfterStartDevServerFn>;
9
8
  onBeforeStartDevServerHook: import("@rsbuild/shared").AsyncHook<OnBeforeStartDevServerFn>;
9
+ onAfterStartProdServerHook: import("@rsbuild/shared").AsyncHook<OnAfterStartProdServerFn>;
10
+ onBeforeStartProdServerHook: import("@rsbuild/shared").AsyncHook<OnBeforeStartProdServerFn>;
10
11
  /** parameters are bundler-related */
11
12
  onAfterBuildHook: import("@rsbuild/shared").AsyncHook<OnAfterBuildFn>;
12
13
  onBeforeBuildHook: import("@rsbuild/shared").AsyncHook<OnBeforeBuildFn<RspackConfig>>;
13
14
  modifyRspackConfigHook: import("@rsbuild/shared").AsyncHook<ModifyRspackConfigFn>;
14
15
  modifyRsbuildConfigHook: import("@rsbuild/shared").AsyncHook<ModifyRsbuildConfigFn<RsbuildConfig>>;
15
- onAfterCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnAfterCreateCompilerFn<Compiler | MultiCompiler>>;
16
+ onAfterCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnAfterCreateCompilerFn>;
16
17
  onBeforeCreateCompilerHook: import("@rsbuild/shared").AsyncHook<OnBeforeCreateCompilerFn<RspackConfig>>;
17
18
  modifyBundlerChainHook: import("@rsbuild/shared").AsyncHook<ModifyBundlerChainFn>;
18
19
  };
@@ -29,6 +29,8 @@ function initHooks() {
29
29
  onDevCompileDoneHook: (0, import_shared.createAsyncHook)(),
30
30
  onAfterStartDevServerHook: (0, import_shared.createAsyncHook)(),
31
31
  onBeforeStartDevServerHook: (0, import_shared.createAsyncHook)(),
32
+ onAfterStartProdServerHook: (0, import_shared.createAsyncHook)(),
33
+ onBeforeStartProdServerHook: (0, import_shared.createAsyncHook)(),
32
34
  /** parameters are bundler-related */
33
35
  onAfterBuildHook: (0, import_shared.createAsyncHook)(),
34
36
  onBeforeBuildHook: (0, import_shared.createAsyncHook)(),
@@ -75,6 +75,8 @@ function getPluginAPI({
75
75
  onBeforeCreateCompiler: hooks.onBeforeCreateCompilerHook.tap,
76
76
  onAfterStartDevServer: hooks.onAfterStartDevServerHook.tap,
77
77
  onBeforeStartDevServer: hooks.onBeforeStartDevServerHook.tap,
78
+ onAfterStartProdServer: hooks.onAfterStartProdServerHook.tap,
79
+ onBeforeStartProdServer: hooks.onBeforeStartProdServerHook.tap,
78
80
  modifyWebpackChain: () => {
79
81
  },
80
82
  modifyWebpackConfig: () => {
@@ -13,7 +13,18 @@ export declare function inspectConfig({
13
13
  rsbuildConfig: string;
14
14
  bundlerConfigs: string[];
15
15
  origin: {
16
- rsbuildConfig: Readonly<import("@rsbuild/shared").RsbuildConfig>;
16
+ rsbuildConfig: {
17
+ pluginNames: string[];
18
+ dev?: import("@rsbuild/shared").DevConfig | undefined;
19
+ server?: import("@rsbuild/shared").ServerConfig | undefined;
20
+ html?: import("@rsbuild/shared").HtmlConfig | undefined;
21
+ tools?: import("@rsbuild/shared").ToolsConfig | undefined;
22
+ source?: import("@rsbuild/shared").SourceConfig | undefined;
23
+ output?: import("@rsbuild/shared").OutputConfig | undefined;
24
+ security?: import("@rsbuild/shared").SecurityConfig | undefined;
25
+ performance?: import("@rsbuild/shared").PerformanceConfig | undefined;
26
+ plugins?: import("@rsbuild/shared").RsbuildPlugin[] | undefined;
27
+ };
17
28
  bundlerConfigs: RspackConfig[];
18
29
  };
19
30
  }>;
@@ -36,13 +36,17 @@ async function inspectConfig({
36
36
  } else if (!process.env.NODE_ENV) {
37
37
  process.env.NODE_ENV = "development";
38
38
  }
39
+ const rsbuildDebugConfig = {
40
+ ...context.config,
41
+ pluginNames: pluginStore.plugins.map((p) => p.name)
42
+ };
39
43
  const rspackConfigs = bundlerConfigs || (await (0, import_initConfigs.initConfigs)({
40
44
  context,
41
45
  pluginStore,
42
46
  rsbuildOptions
43
47
  })).rspackConfigs;
44
48
  const rawRsbuildConfig = await (0, import_shared.stringifyConfig)(
45
- context.config,
49
+ rsbuildDebugConfig,
46
50
  inspectOptions.verbose
47
51
  );
48
52
  const rawBundlerConfigs = await Promise.all(
@@ -70,7 +74,7 @@ async function inspectConfig({
70
74
  rsbuildConfig: rawRsbuildConfig,
71
75
  bundlerConfigs: rawBundlerConfigs,
72
76
  origin: {
73
- rsbuildConfig: context.config,
77
+ rsbuildConfig: rsbuildDebugConfig,
74
78
  bundlerConfigs: rspackConfigs
75
79
  }
76
80
  };
@@ -34,13 +34,12 @@ module.exports = __toCommonJS(rspackConfig_exports);
34
34
  var import_shared = require("@rsbuild/shared");
35
35
  var import_shared2 = require("../shared");
36
36
  async function modifyRspackConfig(context, rspackConfig, utils) {
37
- var _a;
38
37
  (0, import_shared.debug)("modify Rspack config");
39
38
  let [modifiedConfig] = await context.hooks.modifyRspackConfigHook.call(
40
39
  rspackConfig,
41
40
  utils
42
41
  );
43
- if ((_a = context.config.tools) == null ? void 0 : _a.rspack) {
42
+ if (context.config.tools?.rspack) {
44
43
  modifiedConfig = (0, import_shared.mergeChainedOptions)({
45
44
  defaults: modifiedConfig,
46
45
  options: context.config.tools.rspack,
@@ -109,13 +108,19 @@ async function generateRspackConfig({
109
108
  context
110
109
  }) {
111
110
  const chainUtils = await getChainUtils(target);
112
- const { BannerPlugin, DefinePlugin, ProvidePlugin } = await Promise.resolve().then(() => __toESM(require("@rspack/core")));
111
+ const {
112
+ BannerPlugin,
113
+ DefinePlugin,
114
+ ProvidePlugin,
115
+ HotModuleReplacementPlugin
116
+ } = await Promise.resolve().then(() => __toESM(require("@rspack/core")));
113
117
  const chain = await (0, import_shared.modifyBundlerChain)(context, {
114
118
  ...chainUtils,
115
119
  bundler: {
116
120
  BannerPlugin,
117
121
  DefinePlugin,
118
- ProvidePlugin
122
+ ProvidePlugin,
123
+ HotModuleReplacementPlugin
119
124
  }
120
125
  });
121
126
  let rspackConfig = chain.toConfig();
@@ -2,4 +2,5 @@ export { getRspackVersion } from './shared';
2
2
  export { rspackProvider } from './provider';
3
3
  export type { RspackProvider } from './provider';
4
4
  export type { Rspack, RspackConfig } from '@rsbuild/shared';
5
- export { createPublicContext, createContextByConfig, updateContextByNormalizedConfig } from './core/createContext';
5
+ export { createPublicContext, createContextByConfig } from './core/createContext';
6
+ export { initRsbuildConfig } from './core/initConfigs';
@@ -21,18 +21,19 @@ __export(rspack_provider_exports, {
21
21
  createContextByConfig: () => import_createContext.createContextByConfig,
22
22
  createPublicContext: () => import_createContext.createPublicContext,
23
23
  getRspackVersion: () => import_shared.getRspackVersion,
24
- rspackProvider: () => import_provider.rspackProvider,
25
- updateContextByNormalizedConfig: () => import_createContext.updateContextByNormalizedConfig
24
+ initRsbuildConfig: () => import_initConfigs.initRsbuildConfig,
25
+ rspackProvider: () => import_provider.rspackProvider
26
26
  });
27
27
  module.exports = __toCommonJS(rspack_provider_exports);
28
28
  var import_shared = require("./shared");
29
29
  var import_provider = require("./provider");
30
30
  var import_createContext = require("./core/createContext");
31
+ var import_initConfigs = require("./core/initConfigs");
31
32
  // Annotate the CommonJS export names for ESM import in node:
32
33
  0 && (module.exports = {
33
34
  createContextByConfig,
34
35
  createPublicContext,
35
36
  getRspackVersion,
36
- rspackProvider,
37
- updateContextByNormalizedConfig
37
+ initRsbuildConfig,
38
+ rspackProvider
38
39
  });
@@ -164,7 +164,6 @@ const pluginCss = () => {
164
164
  });
165
165
  api.modifyRspackConfig(
166
166
  async (rspackConfig, { isProd, isServer, isWebWorker }) => {
167
- var _a;
168
167
  const config = api.getNormalizedConfig();
169
168
  if (!enableNativeCss(config)) {
170
169
  (0, import_shared.setConfig)(rspackConfig, "experiments.css", false);
@@ -183,7 +182,7 @@ const pluginCss = () => {
183
182
  localIdentName,
184
183
  exportsOnly: isServer || isWebWorker
185
184
  });
186
- const rules = (_a = rspackConfig.module) == null ? void 0 : _a.rules;
185
+ const rules = rspackConfig.module?.rules;
187
186
  applyCSSModuleRule(rules, import_shared.CSS_REGEX, config);
188
187
  }
189
188
  );
@@ -63,10 +63,9 @@ function pluginLess() {
63
63
  rule.use(utils.CHAIN_ID.USE.LESS).loader(utils.getCompiledPath("less-loader")).options(options);
64
64
  });
65
65
  api.modifyRspackConfig(async (rspackConfig) => {
66
- var _a;
67
66
  const { applyCSSModuleRule } = await Promise.resolve().then(() => __toESM(require("./css")));
68
67
  const config = api.getNormalizedConfig();
69
- const rules = (_a = rspackConfig.module) == null ? void 0 : _a.rules;
68
+ const rules = rspackConfig.module?.rules;
70
69
  applyCSSModuleRule(rules, import_shared.LESS_REGEX, config);
71
70
  });
72
71
  }
@@ -36,12 +36,9 @@ const pluginProgress = () => ({
36
36
  name: "rsbuild:progress",
37
37
  setup(api) {
38
38
  api.modifyBundlerChain(async (chain, { target, CHAIN_ID }) => {
39
- var _a;
40
39
  const config = api.getNormalizedConfig();
41
- const options = (_a = config.dev.progressBar) != null ? _a : (
42
- // enable progress bar in production by default
43
- (0, import_shared.isProd)()
44
- );
40
+ const options = config.dev.progressBar ?? // enable progress bar in production by default
41
+ (0, import_shared.isProd)();
45
42
  if (!options) {
46
43
  return;
47
44
  }
@@ -52,8 +52,7 @@ const stopProfiler = (output, profileSession) => {
52
52
  const pluginRspackProfile = () => ({
53
53
  name: "rsbuild:rspack-profile",
54
54
  setup(api) {
55
- var _a;
56
- const RSPACK_PROFILE = (_a = process.env.RSPACK_PROFILE) == null ? void 0 : _a.toUpperCase();
55
+ const RSPACK_PROFILE = process.env.RSPACK_PROFILE?.toUpperCase();
57
56
  if (!RSPACK_PROFILE) {
58
57
  return;
59
58
  }
@@ -68,10 +68,9 @@ function pluginSass() {
68
68
  }).end().use(utils.CHAIN_ID.USE.SASS).loader(utils.getCompiledPath("sass-loader")).options(options);
69
69
  });
70
70
  api.modifyRspackConfig(async (rspackConfig) => {
71
- var _a;
72
71
  const { applyCSSModuleRule } = await Promise.resolve().then(() => __toESM(require("./css")));
73
72
  const config = api.getNormalizedConfig();
74
- const rules = (_a = rspackConfig.module) == null ? void 0 : _a.rules;
73
+ const rules = rspackConfig.module?.rules;
75
74
  applyCSSModuleRule(rules, import_shared.SASS_REGEX, config);
76
75
  });
77
76
  }
@@ -123,19 +123,19 @@ async function applyCoreJs(swcConfig, chain, polyfillMode) {
123
123
  });
124
124
  }
125
125
  function applyTransformImport(swcConfig, pluginImport) {
126
- var _a, _b, _c;
126
+ var _a;
127
127
  if (pluginImport !== false && pluginImport) {
128
- (_a = swcConfig.rspackExperiments) != null ? _a : swcConfig.rspackExperiments = {};
129
- (_c = (_b = swcConfig.rspackExperiments).import) != null ? _c : _b.import = [];
128
+ swcConfig.rspackExperiments ?? (swcConfig.rspackExperiments = {});
129
+ (_a = swcConfig.rspackExperiments).import ?? (_a.import = []);
130
130
  swcConfig.rspackExperiments.import.push(...pluginImport);
131
131
  }
132
132
  }
133
133
  function applyDecorator(swcConfig, enableLatestDecorators) {
134
- var _a, _b;
134
+ var _a;
135
135
  if (enableLatestDecorators) {
136
136
  import_shared.logger.warn("Cannot use latestDecorator in Rspack mode.");
137
137
  }
138
- (_b = (_a = swcConfig.jsc).transform) != null ? _b : _a.transform = {};
138
+ (_a = swcConfig.jsc).transform ?? (_a.transform = {});
139
139
  swcConfig.jsc.transform.legacyDecorator = true;
140
140
  swcConfig.jsc.transform.decoratorMetadata = true;
141
141
  }
@@ -1,6 +1,6 @@
1
- import { type RsbuildProvider, type RspackConfig, type RspackCompiler, type RspackMultiCompiler } from '@rsbuild/shared';
1
+ import { type RsbuildProvider, type RspackConfig } from '@rsbuild/shared';
2
2
  import type { RsbuildConfig, NormalizedConfig } from '../types';
3
- export type RspackProvider = RsbuildProvider<RsbuildConfig, RspackConfig, NormalizedConfig, RspackCompiler | RspackMultiCompiler>;
3
+ export type RspackProvider = RsbuildProvider<RsbuildConfig, RspackConfig, NormalizedConfig>;
4
4
  export declare function rspackProvider({
5
5
  rsbuildConfig: originalRsbuildConfig
6
6
  }: {
@@ -66,6 +66,7 @@ function rspackProvider({
66
66
  async startDevServer(options) {
67
67
  const { startDevServer } = await Promise.resolve().then(() => __toESM(require("../server/devServer")));
68
68
  const { createDevMiddleware } = await Promise.resolve().then(() => __toESM(require("./core/createCompiler")));
69
+ await (0, import_initConfigs.initRsbuildConfig)({ context, pluginStore });
69
70
  return startDevServer(
70
71
  { context, pluginStore, rsbuildOptions },
71
72
  createDevMiddleware,
@@ -74,6 +75,7 @@ function rspackProvider({
74
75
  },
75
76
  async preview(options) {
76
77
  const { startProdServer } = await Promise.resolve().then(() => __toESM(require("../server/prodServer")));
78
+ await (0, import_initConfigs.initRsbuildConfig)({ context, pluginStore });
77
79
  return startProdServer(context, context.config, options);
78
80
  },
79
81
  async build(options) {
@@ -81,7 +81,7 @@ const getRspackVersion = async () => {
81
81
  try {
82
82
  const core = require.resolve("@rspack/core");
83
83
  const pkg = await Promise.resolve().then(() => __toESM(require((0, import_path.join)(core, "../../package.json"))));
84
- return pkg == null ? void 0 : pkg.version;
84
+ return pkg?.version;
85
85
  } catch (err) {
86
86
  console.error(err);
87
87
  return "";
@@ -36,10 +36,10 @@ var import_socketServer = __toESM(require("./socketServer"));
36
36
  const noop = () => {
37
37
  };
38
38
  function getHMRClientPath(client) {
39
- const protocol = (client == null ? void 0 : client.protocol) ? `&protocol=${client.protocol}` : "";
40
- const host = (client == null ? void 0 : client.host) ? `&host=${client.host}` : "";
41
- const path = (client == null ? void 0 : client.path) ? `&path=${client.path}` : "";
42
- const port = (client == null ? void 0 : client.port) ? `&port=${client.port}` : "";
39
+ const protocol = client?.protocol ? `&protocol=${client.protocol}` : "";
40
+ const host = client?.host ? `&host=${client.host}` : "";
41
+ const path = client?.path ? `&path=${client.path}` : "";
42
+ const port = client?.port ? `&port=${client.port}` : "";
43
43
  const clientEntry = `${require.resolve("@rsbuild/core/client/hmr")}?${host}${path}${port}${protocol}`;
44
44
  return clientEntry;
45
45
  }
@@ -63,9 +63,8 @@ class DevMiddleware extends import_events.EventEmitter {
63
63
  });
64
64
  }
65
65
  close() {
66
- var _a;
67
66
  this.socketServer.close();
68
- (_a = this.middleware) == null ? void 0 : _a.close(noop);
67
+ this.middleware?.close(noop);
69
68
  }
70
69
  sockWrite(type, data) {
71
70
  this.socketServer.sockWrite(type, data);
@@ -41,11 +41,10 @@ class SocketServer {
41
41
  }
42
42
  // create socket, install socket handler, bind socket event
43
43
  prepare(app) {
44
- var _a;
45
44
  this.app = app;
46
45
  this.wsServer = new import_ws.default.Server({
47
46
  noServer: true,
48
- path: (_a = this.options.client) == null ? void 0 : _a.path
47
+ path: this.options.client?.path
49
48
  });
50
49
  this.app.on("upgrade", (req, sock, head) => {
51
50
  if (!this.wsServer.shouldHandle(req)) {
@@ -3,8 +3,9 @@
3
3
  /// <reference types="node" />
4
4
  import { Server } from 'http';
5
5
  import type { ListenOptions } from 'net';
6
- import { RsbuildDevServerOptions, CreateDevMiddlewareReturns, DevServerContext, StartDevServerOptions, StartServerResult } from '@rsbuild/shared';
6
+ import { RsbuildDevServerOptions, CreateDevMiddlewareReturns, StartDevServerOptions, StartServerResult } from '@rsbuild/shared';
7
7
  import connect from '@rsbuild/shared/connect';
8
+ import type { Context } from '../types';
8
9
  export declare class RsbuildDevServer {
9
10
  private readonly dev;
10
11
  private readonly devMiddleware;
@@ -21,12 +22,10 @@ export declare class RsbuildDevServer {
21
22
  close(): void;
22
23
  }
23
24
  export declare function startDevServer<Options extends {
24
- context: DevServerContext;
25
+ context: Context;
25
26
  }>(options: Options, createDevMiddleware: (options: Options, compiler: StartDevServerOptions['compiler']) => Promise<CreateDevMiddlewareReturns>, {
26
- open,
27
27
  compiler: customCompiler,
28
28
  printURLs,
29
- strictPort,
30
29
  logger: customLogger,
31
30
  getPortSilently
32
31
  }?: StartDevServerOptions & {
@@ -94,7 +94,7 @@ class RsbuildDevServer {
94
94
  this.middlewares.use((req, res, next) => {
95
95
  res.setHeader("Access-Control-Allow-Origin", "*");
96
96
  const path = req.url ? import_url.default.parse(req.url).pathname : "";
97
- if (path == null ? void 0 : path.includes("hot-update")) {
97
+ if (path?.includes("hot-update")) {
98
98
  res.setHeader("Access-Control-Allow-Credentials", "false");
99
99
  }
100
100
  const confHeaders = dev.headers;
@@ -143,7 +143,7 @@ class RsbuildDevServer {
143
143
  }
144
144
  listen(options, listener) {
145
145
  const callback = () => {
146
- listener == null ? void 0 : listener();
146
+ listener?.();
147
147
  };
148
148
  if (typeof options === "object") {
149
149
  this.app.listen(options, callback);
@@ -157,35 +157,30 @@ class RsbuildDevServer {
157
157
  }
158
158
  }
159
159
  async function startDevServer(options, createDevMiddleware, {
160
- open,
161
160
  compiler: customCompiler,
162
161
  printURLs = true,
163
- strictPort = false,
164
162
  logger: customLogger,
165
163
  getPortSilently
166
164
  } = {}) {
167
- var _a, _b, _c, _d;
168
165
  if (!process.env.NODE_ENV) {
169
166
  process.env.NODE_ENV = "development";
170
167
  }
171
168
  const rsbuildConfig = options.context.config;
172
- const logger = customLogger != null ? customLogger : import_shared.logger;
169
+ const logger = customLogger ?? import_shared.logger;
173
170
  const { devServerConfig, port, host, https } = await (0, import_shared.getDevOptions)({
174
171
  rsbuildConfig,
175
- strictPort,
176
172
  getPortSilently
177
173
  });
178
174
  options.context.devServer = {
179
175
  hostname: host,
180
176
  port,
181
- https,
182
- open
177
+ https
183
178
  };
184
179
  const protocol = https ? "https" : "http";
185
180
  let urls = (0, import_shared.getAddressUrls)(protocol, port, host);
186
181
  const routes = (0, import_shared.formatRoutes)(
187
182
  options.context.entry,
188
- (_b = (_a = rsbuildConfig.output) == null ? void 0 : _a.distPath) == null ? void 0 : _b.html
183
+ rsbuildConfig.output?.distPath?.html
189
184
  );
190
185
  (0, import_shared.debug)("create dev server");
191
186
  const { devMiddleware, compiler } = await createDevMiddleware(
@@ -198,7 +193,7 @@ async function startDevServer(options, createDevMiddleware, {
198
193
  devMiddleware,
199
194
  dev: devServerConfig,
200
195
  output: {
201
- distPath: ((_d = (_c = rsbuildConfig.output) == null ? void 0 : _c.distPath) == null ? void 0 : _d.root) || import_shared.ROOT_DIST_DIR,
196
+ distPath: rsbuildConfig.output?.distPath?.root || import_shared.ROOT_DIST_DIR,
202
197
  publicPaths
203
198
  }
204
199
  });
@@ -67,8 +67,7 @@ const getHtmlFallbackMiddleware = ({ htmlFallback, distPath, callback }) => {
67
67
  outputFileSystem = devMiddleware.outputFileSystem;
68
68
  }
69
69
  const rewrite = (newUrl) => {
70
- var _a;
71
- (_a = import_shared.debug) == null ? void 0 : _a(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
70
+ (0, import_shared.debug)?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`);
72
71
  req.url = newUrl;
73
72
  if (callback) {
74
73
  return callback(req, res, (...args) => {
@@ -4,7 +4,8 @@
4
4
  import type { ListenOptions } from 'net';
5
5
  import { Server } from 'http';
6
6
  import connect from '@rsbuild/shared/connect';
7
- import { type Context, type ServerConfig, type RsbuildConfig, type StartServerResult, type PreviewServerOptions } from '@rsbuild/shared';
7
+ import { type ServerConfig, type RsbuildConfig, type StartServerResult, type PreviewServerOptions } from '@rsbuild/shared';
8
+ import type { Context } from '../types';
8
9
  type RsbuildProdServerOptions = {
9
10
  pwd: string;
10
11
  output: {
@@ -22,12 +23,11 @@ export declare class RsbuildProdServer {
22
23
  private applyDefaultMiddlewares;
23
24
  private applyStaticAssetMiddleware;
24
25
  createHTTPServer(): Promise<Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse> | import("https").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>>;
25
- listen(options?: number | ListenOptions | undefined, listener?: () => void): void;
26
+ listen(options?: number | ListenOptions | undefined, listener?: () => Promise<void>): void;
26
27
  close(): void;
27
28
  }
28
29
  export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig, {
29
30
  printURLs,
30
- strictPort,
31
31
  getPortSilently
32
32
  }?: PreviewServerOptions): Promise<StartServerResult>;
33
33
  export {};
@@ -100,7 +100,7 @@ class RsbuildProdServer {
100
100
  });
101
101
  this.middlewares.use((req, res, next) => {
102
102
  const url = req.url;
103
- if (assetPrefix && (url == null ? void 0 : url.startsWith(assetPrefix))) {
103
+ if (assetPrefix && url?.startsWith(assetPrefix)) {
104
104
  req.url = url.slice(assetPrefix.length);
105
105
  assetMiddleware(req, res, (...args) => {
106
106
  req.url = url;
@@ -122,7 +122,7 @@ class RsbuildProdServer {
122
122
  }
123
123
  listen(options, listener) {
124
124
  const callback = () => {
125
- listener == null ? void 0 : listener();
125
+ listener?.();
126
126
  };
127
127
  if (typeof options === "object") {
128
128
  this.app.listen(options, callback);
@@ -134,28 +134,23 @@ class RsbuildProdServer {
134
134
  this.app.close();
135
135
  }
136
136
  }
137
- async function startProdServer(context, rsbuildConfig, {
138
- printURLs = true,
139
- strictPort = false,
140
- getPortSilently
141
- } = {}) {
142
- var _a, _b, _c;
137
+ async function startProdServer(context, rsbuildConfig, { printURLs = true, getPortSilently } = {}) {
143
138
  if (!process.env.NODE_ENV) {
144
139
  process.env.NODE_ENV = "production";
145
140
  }
146
141
  const { serverConfig, port, host, https } = await (0, import_shared.getServerOptions)({
147
142
  rsbuildConfig,
148
- strictPort,
149
143
  getPortSilently
150
144
  });
151
145
  const server = new RsbuildProdServer({
152
146
  pwd: context.rootPath,
153
147
  output: {
154
- path: ((_b = (_a = rsbuildConfig.output) == null ? void 0 : _a.distPath) == null ? void 0 : _b.root) || import_shared.ROOT_DIST_DIR,
155
- assetPrefix: (_c = rsbuildConfig.output) == null ? void 0 : _c.assetPrefix
148
+ path: rsbuildConfig.output?.distPath?.root || import_shared.ROOT_DIST_DIR,
149
+ assetPrefix: rsbuildConfig.output?.assetPrefix
156
150
  },
157
151
  serverConfig
158
152
  });
153
+ await context.hooks.onBeforeStartProdServerHook.call();
159
154
  const httpServer = await server.createHTTPServer();
160
155
  await server.onInit(httpServer);
161
156
  return new Promise((resolve) => {
@@ -164,14 +159,17 @@ async function startProdServer(context, rsbuildConfig, {
164
159
  host,
165
160
  port
166
161
  },
167
- () => {
168
- var _a2, _b2;
162
+ async () => {
163
+ const routes = (0, import_shared.formatRoutes)(
164
+ context.entry,
165
+ rsbuildConfig.output?.distPath?.html
166
+ );
167
+ await context.hooks.onAfterStartProdServerHook.call({
168
+ port,
169
+ routes
170
+ });
169
171
  const urls = (0, import_shared.getAddressUrls)(https ? "https" : "http", port);
170
172
  if (printURLs) {
171
- const routes = (0, import_shared.formatRoutes)(
172
- context.entry,
173
- (_b2 = (_a2 = rsbuildConfig.output) == null ? void 0 : _a2.distPath) == null ? void 0 : _b2.html
174
- );
175
173
  (0, import_shared.printServerURLs)(
176
174
  (0, import_shared.isFunction)(printURLs) ? printURLs(urls) : urls,
177
175
  routes
@@ -25,7 +25,6 @@ module.exports = __toCommonJS(proxy_exports);
25
25
  var import_http_proxy_middleware = require("@rsbuild/shared/http-proxy-middleware");
26
26
  var import_shared = require("@rsbuild/shared");
27
27
  function formatProxyOptions(proxyOptions) {
28
- var _a;
29
28
  const ret = [];
30
29
  if (Array.isArray(proxyOptions)) {
31
30
  ret.push(...proxyOptions);
@@ -48,7 +47,7 @@ function formatProxyOptions(proxyOptions) {
48
47
  }
49
48
  const handleError = (err) => import_shared.logger.error(err);
50
49
  for (const opts of ret) {
51
- (_a = opts.onError) != null ? _a : opts.onError = handleError;
50
+ opts.onError ?? (opts.onError = handleError);
52
51
  }
53
52
  return ret;
54
53
  }
package/dist/types.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { Context as BaseContext, RsbuildConfig, NormalizedConfig, DefaultRsbuildPluginAPI, RsbuildPlugin as BaseRsbuildPlugin } from '@rsbuild/shared';
2
2
  import type { Hooks } from './rspack-provider/core/initHooks';
3
- import type { RspackConfig, RspackCompiler, RspackMultiCompiler } from '@rsbuild/shared';
4
- export interface RsbuildPluginAPI extends DefaultRsbuildPluginAPI<RsbuildConfig, NormalizedConfig, RspackConfig, RspackCompiler | RspackMultiCompiler> {}
3
+ import type { RspackConfig } from '@rsbuild/shared';
4
+ export interface RsbuildPluginAPI extends DefaultRsbuildPluginAPI<RsbuildConfig, NormalizedConfig, RspackConfig> {}
5
5
  export type RsbuildPlugin<T = RsbuildPluginAPI> = BaseRsbuildPlugin<T>;
6
6
  /** The inner context. */
7
7
  export type Context = BaseContext & {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
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": {
@@ -58,12 +58,12 @@
58
58
  "types.d.ts"
59
59
  ],
60
60
  "dependencies": {
61
- "@rspack/core": "0.4.0",
61
+ "@rspack/core": "0.4.0-canary-d45e3e0-20231128075052",
62
62
  "core-js": "~3.32.2",
63
63
  "html-webpack-plugin": "npm:html-rspack-plugin@5.5.7",
64
64
  "postcss": "8.4.31",
65
65
  "semver": "^7.5.4",
66
- "@rsbuild/shared": "0.1.2"
66
+ "@rsbuild/shared": "0.1.4"
67
67
  },
68
68
  "devDependencies": {
69
69
  "@types/node": "^16",