@rsbuild/core 0.2.10 → 0.2.12

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 (36) hide show
  1. package/dist/cli/commands.js +1 -1
  2. package/dist/cli/prepare.js +1 -1
  3. package/dist/client/hmr.js +2 -3
  4. package/dist/index.d.ts +1 -1
  5. package/dist/plugins/entry.js +28 -1
  6. package/dist/plugins/html.js +10 -4
  7. package/dist/plugins/index.js +2 -1
  8. package/dist/{provider/plugins → plugins}/server.d.ts +1 -1
  9. package/dist/{provider/plugins → plugins}/server.js +8 -27
  10. package/dist/plugins/splitChunks.d.ts +2 -0
  11. package/dist/plugins/splitChunks.js +15 -1
  12. package/dist/provider/core/createCompiler.d.ts +2 -2
  13. package/dist/provider/core/createContext.d.ts +6 -6
  14. package/dist/provider/core/createContext.js +1 -1
  15. package/dist/provider/core/devMiddleware.d.ts +1 -1
  16. package/dist/provider/core/devMiddleware.js +3 -6
  17. package/dist/provider/core/initConfigs.d.ts +2 -2
  18. package/dist/provider/core/initPlugins.d.ts +3 -2
  19. package/dist/provider/core/initPlugins.js +8 -1
  20. package/dist/provider/core/rspackConfig.d.ts +2 -2
  21. package/dist/provider/index.d.ts +1 -1
  22. package/dist/provider/plugins/css.d.ts +2 -2
  23. package/dist/provider/plugins/swc.js +1 -5
  24. package/dist/provider/plugins/transition.js +8 -0
  25. package/dist/provider/shared.js +1 -1
  26. package/dist/rspack/preload/HtmlPreloadOrPrefetchPlugin.js +4 -5
  27. package/dist/server/compilerDevMiddleware.js +2 -2
  28. package/dist/server/devServer.d.ts +4 -4
  29. package/dist/server/devServer.js +4 -3
  30. package/dist/server/helper.d.ts +61 -0
  31. package/dist/server/helper.js +124 -0
  32. package/dist/server/prodServer.d.ts +3 -3
  33. package/dist/server/prodServer.js +4 -3
  34. package/dist/server/socketServer.js +1 -1
  35. package/dist/types.d.ts +2 -2
  36. package/package.json +3 -3
@@ -83,7 +83,7 @@ async function init({
83
83
  }
84
84
  }
85
85
  function runCli() {
86
- import_commander.program.name("rsbuild").usage("<command> [options]").version("0.2.10");
86
+ import_commander.program.name("rsbuild").usage("<command> [options]").version("0.2.12");
87
87
  import_commander.program.command("dev").option("--open", "open the page in browser on startup").option(
88
88
  "--port <port>",
89
89
  "specify a port number for Rsbuild Server to listen"
@@ -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.2.10"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.2.12"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
@@ -373,7 +373,7 @@ function createSocketUrl(resourceQuery) {
373
373
  }
374
374
  function formatURL(param) {
375
375
  var port = param.port, protocol = param.protocol, hostname = param.hostname, pathname = param.pathname;
376
- if (window.URL) {
376
+ if (typeof URL !== "undefined") {
377
377
  var url = new URL("http://localhost");
378
378
  url.port = port;
379
379
  url.hostname = hostname;
@@ -394,7 +394,6 @@ function getSocketUrl(urlParts, location) {
394
394
  });
395
395
  }
396
396
  // src/client/hmr/index.ts
397
- var hadRuntimeError = false;
398
397
  var socketUrl = createSocketUrl(__resourceQuery);
399
398
  var isFirstCompilation = true;
400
399
  var mostRecentCompilationHash = null;
@@ -489,7 +488,7 @@ function tryApplyUpdates() {
489
488
  return;
490
489
  }
491
490
  function handleApplyUpdates(err, updatedModules) {
492
- var wantsForcedReload = err || !updatedModules || hadRuntimeError;
491
+ var wantsForcedReload = err || !updatedModules;
493
492
  if (wantsForcedReload) {
494
493
  window.location.reload();
495
494
  return;
package/dist/index.d.ts CHANGED
@@ -8,4 +8,4 @@ export { loadConfig, defineConfig } from './cli/config';
8
8
  export { logger, mergeRsbuildConfig } from '@rsbuild/shared';
9
9
  export type { Rspack } from './provider';
10
10
  export type { RsbuildConfig, NormalizedConfig, RsbuildPlugin, RsbuildPluginAPI, } from './types';
11
- 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';
11
+ export type { RsbuildMode, RsbuildEntry, RsbuildTarget, RsbuildContext, RsbuildInstance, CreateRsbuildOptions, InspectConfigOptions, OnExitFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnBeforeCreateCompilerFn, OnDevCompileDoneFn, ModifyRsbuildConfigFn, } from '@rsbuild/shared';
@@ -31,12 +31,39 @@ const pluginEntry = () => ({
31
31
  const { preEntry } = config.source;
32
32
  const injectCoreJsEntry = config.output.polyfill === "entry" && !isServer && !isServiceWorker;
33
33
  Object.keys(entry).forEach((entryName) => {
34
- const appendEntry = (file) => chain.entry(entryName).add(file);
34
+ const entryImport = [];
35
+ let entryDescription = null;
36
+ const appendEntry = (item) => {
37
+ if (typeof item === "string") {
38
+ entryImport.push(item);
39
+ return;
40
+ }
41
+ if (item.import) {
42
+ entryImport.push(...(0, import_shared.castArray)(item.import));
43
+ }
44
+ if (entryDescription) {
45
+ Object.assign(entryDescription, item);
46
+ } else {
47
+ entryDescription = item;
48
+ }
49
+ };
35
50
  preEntry.forEach(appendEntry);
36
51
  if (injectCoreJsEntry) {
37
52
  appendEntry((0, import_shared.createVirtualModule)('import "core-js";'));
38
53
  }
39
54
  (0, import_shared.castArray)(entry[entryName]).forEach(appendEntry);
55
+ chain.entryPoints.set(entryName, {
56
+ // @ts-expect-error EntryDescription type mismatch
57
+ values() {
58
+ if (entryDescription) {
59
+ return {
60
+ ...entryDescription,
61
+ import: entryImport
62
+ };
63
+ }
64
+ return entryImport;
65
+ }
66
+ });
40
67
  });
41
68
  });
42
69
  api.onBeforeCreateCompiler(({ bundlerConfigs }) => {
@@ -136,11 +136,13 @@ function getTemplateParameters(entryName, config, assetPrefix) {
136
136
  };
137
137
  }
138
138
  function getChunks(entryName, entryValue) {
139
- const dependOn = [];
140
139
  if ((0, import_shared.isPlainObject)(entryValue)) {
141
- dependOn.push(...entryValue.dependOn);
140
+ const { dependOn } = entryValue;
141
+ if (Array.isArray(dependOn)) {
142
+ return [...dependOn, entryName];
143
+ }
142
144
  }
143
- return [...dependOn, entryName];
145
+ return [entryName];
144
146
  }
145
147
  const applyInjectTags = (api) => {
146
148
  api.modifyBundlerChain(async (chain, { CHAIN_ID }) => {
@@ -194,7 +196,11 @@ const pluginHtml = () => ({
194
196
  await Promise.all(
195
197
  entryNames.map(async (entryName) => {
196
198
  const entryValue = entries[entryName].values();
197
- const chunks = getChunks(entryName, entryValue);
199
+ const chunks = getChunks(
200
+ entryName,
201
+ // @ts-expect-error EntryDescription type mismatch
202
+ entryValue
203
+ );
198
204
  const inject = getInject(entryName, config);
199
205
  const filename = htmlPaths[entryName];
200
206
  const { templatePath, templateContent } = await getTemplate(
@@ -53,7 +53,8 @@ const plugins = {
53
53
  networkPerformance: () => Promise.resolve().then(() => __toESM(require("./networkPerformance"))).then((m) => m.pluginNetworkPerformance()),
54
54
  preloadOrPrefetch: () => Promise.resolve().then(() => __toESM(require("./preloadOrPrefetch"))).then((m) => m.pluginPreloadOrPrefetch()),
55
55
  performance: () => Promise.resolve().then(() => __toESM(require("./performance"))).then((m) => m.pluginPerformance()),
56
- define: () => Promise.resolve().then(() => __toESM(require("./define"))).then((m) => m.pluginDefine())
56
+ define: () => Promise.resolve().then(() => __toESM(require("./define"))).then((m) => m.pluginDefine()),
57
+ server: () => Promise.resolve().then(() => __toESM(require("./server"))).then((m) => m.pluginServer())
57
58
  };
58
59
  // Annotate the CommonJS export names for ESM import in node:
59
60
  0 && (module.exports = {
@@ -1,2 +1,2 @@
1
- import type { RsbuildPlugin } from '../../types';
1
+ import type { RsbuildPlugin } from '../types';
2
2
  export declare const pluginServer: () => RsbuildPlugin;
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,49 +15,32 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
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
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
  var server_exports = {};
30
20
  __export(server_exports, {
31
21
  pluginServer: () => pluginServer
32
22
  });
33
23
  module.exports = __toCommonJS(server_exports);
34
- var import_fs = __toESM(require("fs"));
24
+ var import_shared = require("@rsbuild/shared");
35
25
  var import_path = require("path");
36
26
  const pluginServer = () => ({
37
27
  name: "rsbuild:server",
38
28
  setup(api) {
39
- api.modifyBundlerChain(async (chain, { isProd }) => {
29
+ api.onBeforeBuild(async () => {
40
30
  const config = api.getNormalizedConfig();
41
- if (isProd && config.server?.publicDir) {
31
+ if (config.server?.publicDir) {
42
32
  const { name, copyOnBuild } = config.server?.publicDir;
43
33
  if (!copyOnBuild || !name) {
44
34
  return;
45
35
  }
46
36
  const publicDir = (0, import_path.isAbsolute)(name) ? name : (0, import_path.join)(api.context.rootPath, name);
47
- const publicPattern = [
48
- {
49
- from: publicDir,
50
- to: "",
51
- noErrorOnMissing: true
52
- }
53
- ];
54
- if (!import_fs.default.existsSync(publicDir)) {
37
+ if (!import_shared.fse.existsSync(publicDir)) {
55
38
  return;
56
39
  }
57
- const { CopyRspackPlugin } = await Promise.resolve().then(() => __toESM(require("@rspack/core")));
58
- chain.plugin("public-dir").use(CopyRspackPlugin, [
59
- {
60
- patterns: publicPattern
61
- }
62
- ]);
40
+ await import_shared.fse.copy(publicDir, api.context.distPath, {
41
+ // dereference symlinks
42
+ dereference: true
43
+ });
63
44
  }
64
45
  });
65
46
  }
@@ -1,2 +1,4 @@
1
1
  import type { RsbuildPlugin } from '../types';
2
+ export declare const MODULE_PATH_REGEX: RegExp;
3
+ export declare function getPackageNameFromModulePath(modulePath: string): string | undefined;
2
4
  export declare function pluginSplitChunks(): RsbuildPlugin;
@@ -28,6 +28,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var splitChunks_exports = {};
30
30
  __export(splitChunks_exports, {
31
+ MODULE_PATH_REGEX: () => MODULE_PATH_REGEX,
32
+ getPackageNameFromModulePath: () => getPackageNameFromModulePath,
31
33
  pluginSplitChunks: () => pluginSplitChunks
32
34
  });
33
35
  module.exports = __toCommonJS(splitChunks_exports);
@@ -84,6 +86,16 @@ function splitByExperience(ctx) {
84
86
  }
85
87
  };
86
88
  }
89
+ const MODULE_PATH_REGEX = /[\\/]node_modules[\\/](\.pnpm[\\/])?(?:(@[^[\\/]+)(?:[\\/]))?([^\\/]+)/;
90
+ function getPackageNameFromModulePath(modulePath) {
91
+ const handleModuleContext = modulePath?.match(MODULE_PATH_REGEX);
92
+ if (!handleModuleContext) {
93
+ return void 0;
94
+ }
95
+ const [, , scope, name] = handleModuleContext;
96
+ const packageName = ["npm", (scope ?? "").replace("@", ""), name].filter(Boolean).join(".");
97
+ return packageName;
98
+ }
87
99
  function splitByModule(ctx) {
88
100
  const { override, userDefinedCacheGroups, defaultConfig } = ctx;
89
101
  return {
@@ -99,7 +111,7 @@ function splitByModule(ctx) {
99
111
  priority: -10,
100
112
  test: import_shared.NODE_MODULES_REGEX,
101
113
  name(module2) {
102
- return module2 ? (0, import_shared.getPackageNameFromModulePath)(module2.context) : void 0;
114
+ return module2 ? getPackageNameFromModulePath(module2.context) : void 0;
103
115
  }
104
116
  },
105
117
  ...override.cacheGroups
@@ -220,5 +232,7 @@ function pluginSplitChunks() {
220
232
  }
221
233
  // Annotate the CommonJS export names for ESM import in node:
222
234
  0 && (module.exports = {
235
+ MODULE_PATH_REGEX,
236
+ getPackageNameFromModulePath,
223
237
  pluginSplitChunks
224
238
  });
@@ -1,8 +1,8 @@
1
1
  import { type RspackConfig, type RspackCompiler, type RspackMultiCompiler, type CreateDevMiddlewareReturns } from '@rsbuild/shared';
2
2
  import { type InitConfigsOptions } from './initConfigs';
3
- import type { Context } from '../../types';
3
+ import type { InternalContext } from '../../types';
4
4
  export declare function createCompiler({ context, rspackConfigs, }: {
5
- context: Context;
5
+ context: InternalContext;
6
6
  rspackConfigs: RspackConfig[];
7
7
  }): Promise<RspackCompiler | RspackMultiCompiler>;
8
8
  export declare function createDevMiddleware(options: InitConfigsOptions, customCompiler?: RspackCompiler | RspackMultiCompiler): Promise<CreateDevMiddlewareReturns>;
@@ -1,13 +1,13 @@
1
- import { RsbuildConfig, type Context as BaseContext, type BundlerType, type NormalizedConfig, type CreateRsbuildOptions } from '@rsbuild/shared';
2
- import type { Context } from '../../types';
1
+ import { RsbuildConfig, type BundlerType, type RsbuildContext, type NormalizedConfig, type CreateRsbuildOptions } from '@rsbuild/shared';
2
+ import type { InternalContext } from '../../types';
3
3
  /**
4
4
  * Create context by config.
5
5
  */
6
- export declare function createContextByConfig(options: Required<CreateRsbuildOptions>, bundlerType: BundlerType, config?: RsbuildConfig): BaseContext;
7
- export declare function updateContextByNormalizedConfig(context: BaseContext, config: NormalizedConfig): void;
8
- export declare function createPublicContext(context: BaseContext): Readonly<BaseContext>;
6
+ export declare function createContextByConfig(options: Required<CreateRsbuildOptions>, bundlerType: BundlerType, config?: RsbuildConfig): RsbuildContext;
7
+ export declare function updateContextByNormalizedConfig(context: RsbuildContext, config: NormalizedConfig): void;
8
+ export declare function createPublicContext(context: RsbuildContext): Readonly<RsbuildContext>;
9
9
  /**
10
10
  * Generate the actual context used in the build,
11
11
  * which can have a lot of overhead and take some side effects.
12
12
  */
13
- export declare function createContext(options: Required<CreateRsbuildOptions>, userRsbuildConfig: RsbuildConfig, bundlerType: BundlerType): Promise<Context>;
13
+ export declare function createContext(options: Required<CreateRsbuildOptions>, userRsbuildConfig: RsbuildConfig, bundlerType: BundlerType): Promise<InternalContext>;
@@ -59,7 +59,7 @@ function createContextByConfig(options, bundlerType, config = {}) {
59
59
  const context = {
60
60
  entry: config.source?.entry || getDefaultEntry(rootPath),
61
61
  targets: config.output?.targets || [],
62
- version: "0.2.10",
62
+ version: "0.2.12",
63
63
  rootPath,
64
64
  distPath,
65
65
  cachePath,
@@ -1,3 +1,3 @@
1
- import { DevMiddleware } from '@rsbuild/shared';
1
+ import { type DevMiddleware } from '@rsbuild/shared';
2
2
  import type { Compiler, MultiCompiler } from '@rspack/core';
3
3
  export declare const getDevMiddleware: (multiCompiler: Compiler | MultiCompiler) => NonNullable<DevMiddleware>;
@@ -37,12 +37,9 @@ function applyHMREntry(compiler, clientPath) {
37
37
  if (!(0, import_shared.isClientCompiler)(compiler)) {
38
38
  return;
39
39
  }
40
- for (const key in compiler.options.entry) {
41
- compiler.options.entry[key].import = [
42
- clientPath,
43
- ...compiler.options.entry[key].import || []
44
- ];
45
- }
40
+ new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
41
+ name: void 0
42
+ }).apply(compiler);
46
43
  }
47
44
  const getDevMiddleware = (multiCompiler) => (options) => {
48
45
  const { hmrClientPath, callbacks, ...restOptions } = options;
@@ -1,7 +1,7 @@
1
1
  import { type PluginStore, type RspackConfig, type CreateRsbuildOptions } from '@rsbuild/shared';
2
- import type { Context, NormalizedConfig } from '../../types';
2
+ import type { InternalContext, NormalizedConfig } from '../../types';
3
3
  export type InitConfigsOptions = {
4
- context: Context;
4
+ context: InternalContext;
5
5
  pluginStore: PluginStore;
6
6
  rsbuildOptions: Required<CreateRsbuildOptions>;
7
7
  };
@@ -1,6 +1,7 @@
1
1
  import { type PluginStore, type RsbuildPluginAPI } from '@rsbuild/shared';
2
- import type { Context } from '../../types';
2
+ import type { InternalContext, NormalizedConfig } from '../../types';
3
+ export declare function getHTMLPathByEntry(entryName: string, config: NormalizedConfig): string;
3
4
  export declare function getPluginAPI({ context, pluginStore, }: {
4
- context: Context;
5
+ context: InternalContext;
5
6
  pluginStore: PluginStore;
6
7
  }): RsbuildPluginAPI;
@@ -18,11 +18,17 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var initPlugins_exports = {};
20
20
  __export(initPlugins_exports, {
21
+ getHTMLPathByEntry: () => getHTMLPathByEntry,
21
22
  getPluginAPI: () => getPluginAPI
22
23
  });
23
24
  module.exports = __toCommonJS(initPlugins_exports);
24
25
  var import_shared = require("@rsbuild/shared");
25
26
  var import_createContext = require("./createContext");
27
+ function getHTMLPathByEntry(entryName, config) {
28
+ const htmlPath = (0, import_shared.getDistPath)(config, "html");
29
+ const filename = config.html.outputStructure === "flat" ? `${entryName}.html` : `${entryName}/index.html`;
30
+ return (0, import_shared.removeLeadingSlash)(`${htmlPath}/${filename}`);
31
+ }
26
32
  function getPluginAPI({
27
33
  context,
28
34
  pluginStore
@@ -51,7 +57,7 @@ function getPluginAPI({
51
57
  const getHTMLPaths = () => {
52
58
  return Object.keys(context.entry).reduce(
53
59
  (prev, key) => {
54
- prev[key] = (0, import_shared.getHTMLPathByEntry)(key, getNormalizedConfig());
60
+ prev[key] = getHTMLPathByEntry(key, getNormalizedConfig());
55
61
  return prev;
56
62
  },
57
63
  {}
@@ -86,5 +92,6 @@ function getPluginAPI({
86
92
  }
87
93
  // Annotate the CommonJS export names for ESM import in node:
88
94
  0 && (module.exports = {
95
+ getHTMLPathByEntry,
89
96
  getPluginAPI
90
97
  });
@@ -1,6 +1,6 @@
1
1
  import { type RspackConfig, type RsbuildTarget } from '@rsbuild/shared';
2
- import type { Context } from '../../types';
2
+ import type { InternalContext } from '../../types';
3
3
  export declare function generateRspackConfig({ target, context, }: {
4
4
  target: RsbuildTarget;
5
- context: Context;
5
+ context: InternalContext;
6
6
  }): Promise<RspackConfig>;
@@ -7,5 +7,5 @@ export { withDefaultConfig } from './config';
7
7
  export { initRsbuildConfig } from './core/initConfigs';
8
8
  export { getPluginAPI } from './core/initPlugins';
9
9
  export { applyBaseCSSRule, applyCSSModuleRule } from './plugins/css';
10
- export type { Context } from '../types';
10
+ export type { InternalContext } from '../types';
11
11
  export { setHTMLPlugin, getHTMLPlugin } from './htmlPluginUtil';
@@ -1,10 +1,10 @@
1
- import { type BundlerChain, type Context, type RspackRule, type ModifyBundlerChainUtils } from '@rsbuild/shared';
1
+ import { type BundlerChain, type RsbuildContext, type RspackRule, type ModifyBundlerChainUtils } from '@rsbuild/shared';
2
2
  import type { RsbuildPlugin, NormalizedConfig } from '../../types';
3
3
  export declare const enableNativeCss: (config: NormalizedConfig) => boolean;
4
4
  export declare function applyBaseCSSRule({ rule, config, context, utils: { target, isProd, isServer, isWebWorker, CHAIN_ID }, importLoaders, }: {
5
5
  rule: ReturnType<BundlerChain['module']['rule']>;
6
6
  config: NormalizedConfig;
7
- context: Context;
7
+ context: RsbuildContext;
8
8
  utils: ModifyBundlerChainUtils;
9
9
  importLoaders?: number;
10
10
  }): Promise<void>;
@@ -49,14 +49,10 @@ async function getDefaultSwcConfig(config, rootPath, target) {
49
49
  preserveAllComments: true
50
50
  },
51
51
  isModule: "unknown",
52
- minify: false,
53
- // for loader, we don't need to minify, we do minification using plugin
54
52
  env: {
55
53
  targets: await (0, import_shared.getBrowserslistWithDefault)(rootPath, config, target)
56
54
  },
57
- sourceMaps: Boolean((0, import_shared.getJsSourceMap)(config)),
58
- exclude: [],
59
- inlineSourcesContent: true
55
+ sourceMaps: Boolean((0, import_shared.getJsSourceMap)(config))
60
56
  };
61
57
  }
62
58
  const pluginSwc = () => ({
@@ -21,6 +21,7 @@ __export(transition_exports, {
21
21
  pluginTransition: () => pluginTransition
22
22
  });
23
23
  module.exports = __toCommonJS(transition_exports);
24
+ var import_shared = require("@rsbuild/shared");
24
25
  const pluginTransition = () => ({
25
26
  name: "rsbuild:transition",
26
27
  setup(api) {
@@ -30,6 +31,13 @@ const pluginTransition = () => ({
30
31
  chain.optimization.chunkIds("deterministic");
31
32
  }
32
33
  });
34
+ api.modifyRspackConfig((config) => {
35
+ (0, import_shared.setConfig)(
36
+ config,
37
+ "experiments.rspackFuture.disableApplyEntryLazily",
38
+ true
39
+ );
40
+ });
33
41
  }
34
42
  });
35
43
  // Annotate the CommonJS export names for ESM import in node:
@@ -73,7 +73,7 @@ const applyDefaultPlugins = (plugins) => (0, import_shared3.awaitableGetter)([
73
73
  plugins.networkPerformance(),
74
74
  plugins.preloadOrPrefetch(),
75
75
  plugins.performance(),
76
- Promise.resolve().then(() => __toESM(require("./plugins/server"))).then((m) => m.pluginServer()),
76
+ plugins.server(),
77
77
  Promise.resolve().then(() => __toESM(require("./plugins/rspackProfile"))).then((m) => m.pluginRspackProfile())
78
78
  ]);
79
79
  const rspackMinVersion = "0.4.0";
@@ -58,11 +58,10 @@ function generateLinks(options, type, compilation, htmlPluginData, HTMLCount) {
58
58
  });
59
59
  const htmlChunks = (
60
60
  // Handle all chunks.
61
- options.type === "all-assets" || HTMLCount === 1 ? extractedChunks : extractedChunks.filter(
62
- (chunk) => (
63
- // TODO: Not yet supported in rspack, maybe we should implement it in another way
64
- // https://github.com/web-infra-dev/rspack/issues/3896
65
- (0, import_helpers.doesChunkBelongToHtml)({
61
+ options.type === "all-assets" || HTMLCount === 1 ? extractedChunks : (
62
+ // Only handle chunks imported by this HtmlWebpackPlugin.
63
+ extractedChunks.filter(
64
+ (chunk) => (0, import_helpers.doesChunkBelongToHtml)({
66
65
  chunk,
67
66
  compilation,
68
67
  htmlPluginData,
@@ -76,13 +76,13 @@ class CompilerDevMiddleware {
76
76
  this.socketServer.updateStats(stats);
77
77
  }
78
78
  };
79
- const enableHMR = this.devOptions.hmr;
79
+ const injectClient = this.devOptions.hmr || this.devOptions.liveReload;
80
80
  const middleware = devMiddleware({
81
81
  headers: devOptions.headers,
82
82
  publicPath: "/",
83
83
  stats: false,
84
84
  callbacks,
85
- hmrClientPath: enableHMR ? getHMRClientPath(devOptions.client) : void 0,
85
+ hmrClientPath: injectClient ? getHMRClientPath(devOptions.client) : void 0,
86
86
  serverSideRender: true,
87
87
  writeToDisk: devOptions.writeToDisk
88
88
  });
@@ -1,12 +1,12 @@
1
- import { CreateDevMiddlewareReturns, StartDevServerOptions, StartServerResult, DevServerAPIs } from '@rsbuild/shared';
2
- import type { Context } from '../types';
1
+ import { StartServerResult, type DevServerAPIs, type StartDevServerOptions, type CreateDevMiddlewareReturns } from '@rsbuild/shared';
2
+ import type { InternalContext } from '../types';
3
3
  export declare function getServerAPIs<Options extends {
4
- context: Context;
4
+ context: InternalContext;
5
5
  }>(options: Options, createDevMiddleware: (options: Options, compiler: StartDevServerOptions['compiler']) => Promise<CreateDevMiddlewareReturns>, { compiler: customCompiler, getPortSilently, }?: StartDevServerOptions & {
6
6
  defaultPort?: number;
7
7
  }): Promise<DevServerAPIs>;
8
8
  export declare function startDevServer<Options extends {
9
- context: Context;
9
+ context: InternalContext;
10
10
  }>(options: Options, createDevMiddleware: (options: Options, compiler: StartDevServerOptions['compiler']) => Promise<CreateDevMiddlewareReturns>, { compiler, printURLs, logger: customLogger, getPortSilently, }?: StartDevServerOptions & {
11
11
  defaultPort?: number;
12
12
  }): Promise<StartServerResult>;
@@ -33,6 +33,7 @@ __export(devServer_exports, {
33
33
  });
34
34
  module.exports = __toCommonJS(devServer_exports);
35
35
  var import_shared = require("@rsbuild/shared");
36
+ var import_helper = require("./helper");
36
37
  var import_connect = __toESM(require("@rsbuild/shared/connect"));
37
38
  var import_restart = require("./restart");
38
39
  var import_httpServer = require("./httpServer");
@@ -46,11 +47,11 @@ async function getServerAPIs(options, createDevMiddleware, {
46
47
  process.env.NODE_ENV = "development";
47
48
  }
48
49
  const rsbuildConfig = options.context.config;
49
- const { devServerConfig, port, host, https } = await (0, import_shared.getDevOptions)({
50
+ const { devServerConfig, port, host, https } = await (0, import_helper.getDevOptions)({
50
51
  rsbuildConfig,
51
52
  getPortSilently
52
53
  });
53
- const defaultRoutes = (0, import_shared.formatRoutes)(
54
+ const defaultRoutes = (0, import_helper.formatRoutes)(
54
55
  options.context.entry,
55
56
  rsbuildConfig.output?.distPath?.html,
56
57
  rsbuildConfig.html?.outputStructure
@@ -141,7 +142,7 @@ async function startDevServer(options, createDevMiddleware, {
141
142
  throw new Error("Please return an array in the `printURLs` function.");
142
143
  }
143
144
  }
144
- (0, import_shared.printServerURLs)(urls, defaultRoutes, logger);
145
+ (0, import_helper.printServerURLs)(urls, defaultRoutes, logger);
145
146
  }
146
147
  const compileMiddlewareAPI = await serverAPIs.startCompile();
147
148
  const devMiddlewares = await serverAPIs.getMiddlewares({
@@ -0,0 +1,61 @@
1
+ /// <reference types="node" />
2
+ import type { Logger, Routes, DevConfig, RsbuildEntry, RsbuildConfig, OutputStructure } from '@rsbuild/shared';
3
+ export declare const formatRoutes: (entry: RsbuildEntry, prefix: string | undefined, outputStructure: OutputStructure | undefined) => Routes;
4
+ export declare function printServerURLs(urls: Array<{
5
+ url: string;
6
+ label: string;
7
+ }>, routes: Routes, logger?: Logger): void;
8
+ /**
9
+ * hmr socket connect path
10
+ */
11
+ export declare const HMR_SOCK_PATH = "/rsbuild-hmr";
12
+ export declare const mergeDevOptions: ({ rsbuildConfig, port, }: {
13
+ rsbuildConfig: RsbuildConfig;
14
+ port: number;
15
+ }) => DevConfig;
16
+ export declare const getServerOptions: ({ rsbuildConfig, getPortSilently, }: {
17
+ rsbuildConfig: RsbuildConfig;
18
+ getPortSilently?: boolean | undefined;
19
+ }) => Promise<{
20
+ port: number;
21
+ host: string;
22
+ https: boolean;
23
+ serverConfig: import("@rsbuild/shared").ServerConfig;
24
+ }>;
25
+ export declare const getDevOptions: ({ rsbuildConfig, getPortSilently, }: {
26
+ rsbuildConfig: RsbuildConfig;
27
+ getPortSilently?: boolean | undefined;
28
+ }) => Promise<{
29
+ devServerConfig: {
30
+ hmr?: boolean | undefined;
31
+ liveReload?: boolean | undefined;
32
+ startUrl?: string | boolean | string[] | undefined;
33
+ beforeStartUrl?: import("@rsbuild/shared").ArrayOrNot<() => void | Promise<void>> | undefined;
34
+ assetPrefix?: string | boolean | undefined;
35
+ progressBar?: boolean | import("@rsbuild/shared").ProgressBarConfig | undefined;
36
+ client?: {
37
+ path?: string | undefined;
38
+ port?: string | undefined;
39
+ host?: string | undefined;
40
+ protocol?: string | undefined;
41
+ } | undefined;
42
+ setupMiddlewares?: ((middlewares: {
43
+ unshift: (...handlers: import("@rsbuild/shared").RequestHandler[]) => void;
44
+ push: (...handlers: import("@rsbuild/shared").RequestHandler[]) => void;
45
+ }, server: import("@rsbuild/shared").ServerAPIs) => void)[] | undefined;
46
+ writeToDisk?: boolean | ((filename: string) => boolean) | undefined;
47
+ compress?: boolean | undefined;
48
+ publicDir?: import("@rsbuild/shared").PublicDir | undefined;
49
+ port?: number | undefined;
50
+ https?: import("https").ServerOptions | undefined;
51
+ host?: string | undefined;
52
+ headers?: Record<string, string | string[]> | undefined;
53
+ htmlFallback?: import("@rsbuild/shared").HtmlFallback | undefined;
54
+ historyApiFallback?: boolean | import("@rsbuild/shared").HistoryApiFallbackOptions | undefined;
55
+ proxy?: import("@rsbuild/shared").ProxyOptions | undefined;
56
+ strictPort?: boolean | undefined;
57
+ };
58
+ port: number;
59
+ host: string;
60
+ https: boolean;
61
+ }>;
@@ -0,0 +1,124 @@
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 helper_exports = {};
20
+ __export(helper_exports, {
21
+ HMR_SOCK_PATH: () => HMR_SOCK_PATH,
22
+ formatRoutes: () => formatRoutes,
23
+ getDevOptions: () => getDevOptions,
24
+ getServerOptions: () => getServerOptions,
25
+ mergeDevOptions: () => mergeDevOptions,
26
+ printServerURLs: () => printServerURLs
27
+ });
28
+ module.exports = __toCommonJS(helper_exports);
29
+ var import_shared = require("@rsbuild/shared");
30
+ const formatRoutes = (entry, prefix, outputStructure) => {
31
+ return Object.keys(entry).map((name) => ({
32
+ name,
33
+ route: (prefix ? `${prefix}/` : "") + // fix case: /html/index/index.html
34
+ (name === "index" && outputStructure !== "nested" ? "" : name)
35
+ })).sort((a) => a.name === "index" ? -1 : 1);
36
+ };
37
+ function printServerURLs(urls, routes, logger = import_shared.logger) {
38
+ let message = "";
39
+ if (routes.length === 1) {
40
+ message = urls.map(
41
+ ({ label, url }) => ` ${`> ${label.padEnd(10)}`}${import_shared.color.cyan(
42
+ (0, import_shared.normalizeUrl)(`${url}/${routes[0].route}`)
43
+ )}
44
+ `
45
+ ).join("");
46
+ } else {
47
+ const maxNameLength = Math.max(...routes.map((r) => r.name.length));
48
+ urls.forEach(({ label, url }, index) => {
49
+ if (index > 0) {
50
+ message += "\n";
51
+ }
52
+ message += ` ${`> ${label}`}
53
+ `;
54
+ routes.forEach((r) => {
55
+ message += ` ${import_shared.color.dim("-")} ${import_shared.color.dim(
56
+ r.name.padEnd(maxNameLength + 4)
57
+ )}${import_shared.color.cyan((0, import_shared.normalizeUrl)(`${url}/${r.route}`))}
58
+ `;
59
+ });
60
+ });
61
+ }
62
+ logger.log(message);
63
+ }
64
+ const HMR_SOCK_PATH = "/rsbuild-hmr";
65
+ const mergeDevOptions = ({
66
+ rsbuildConfig,
67
+ port
68
+ }) => {
69
+ const defaultDevConfig = {
70
+ client: {
71
+ path: HMR_SOCK_PATH,
72
+ port: port.toString(),
73
+ // By default it is set to "location.hostname"
74
+ host: "",
75
+ // By default it is set to "location.protocol === 'https:' ? 'wss' : 'ws'""
76
+ protocol: ""
77
+ },
78
+ writeToDisk: false
79
+ };
80
+ const devConfig = rsbuildConfig.dev ? (0, import_shared.deepmerge)(defaultDevConfig, rsbuildConfig.dev) : defaultDevConfig;
81
+ return devConfig;
82
+ };
83
+ const getServerOptions = async ({
84
+ rsbuildConfig,
85
+ getPortSilently
86
+ }) => {
87
+ const host = rsbuildConfig.server?.host || import_shared.DEFAULT_DEV_HOST;
88
+ const port = await (0, import_shared.getPort)({
89
+ host,
90
+ port: rsbuildConfig.server?.port || import_shared.DEFAULT_PORT,
91
+ strictPort: rsbuildConfig.server?.strictPort || false,
92
+ silent: getPortSilently
93
+ });
94
+ const https = Boolean(rsbuildConfig.server?.https) || false;
95
+ return { port, host, https, serverConfig: rsbuildConfig.server || {} };
96
+ };
97
+ const getDevOptions = async ({
98
+ rsbuildConfig,
99
+ getPortSilently
100
+ }) => {
101
+ const { port, host, https, serverConfig } = await getServerOptions({
102
+ rsbuildConfig,
103
+ getPortSilently
104
+ });
105
+ const devConfig = mergeDevOptions({ rsbuildConfig, port });
106
+ return {
107
+ devServerConfig: {
108
+ ...serverConfig,
109
+ ...devConfig
110
+ },
111
+ port,
112
+ host,
113
+ https
114
+ };
115
+ };
116
+ // Annotate the CommonJS export names for ESM import in node:
117
+ 0 && (module.exports = {
118
+ HMR_SOCK_PATH,
119
+ formatRoutes,
120
+ getDevOptions,
121
+ getServerOptions,
122
+ mergeDevOptions,
123
+ printServerURLs
124
+ });
@@ -1,8 +1,8 @@
1
1
  /// <reference types="node" />
2
- import { Server } from 'http';
2
+ import type { Server } from 'http';
3
3
  import connect from '@rsbuild/shared/connect';
4
4
  import { type ServerConfig, type RsbuildConfig, type StartServerResult, type PreviewServerOptions } from '@rsbuild/shared';
5
- import type { Context } from '../types';
5
+ import type { InternalContext } from '../types';
6
6
  type RsbuildProdServerOptions = {
7
7
  pwd: string;
8
8
  output: {
@@ -21,5 +21,5 @@ export declare class RsbuildProdServer {
21
21
  private applyStaticAssetMiddleware;
22
22
  close(): void;
23
23
  }
24
- export declare function startProdServer(context: Context, rsbuildConfig: RsbuildConfig, { printURLs, getPortSilently }?: PreviewServerOptions): Promise<StartServerResult>;
24
+ export declare function startProdServer(context: InternalContext, rsbuildConfig: RsbuildConfig, { printURLs, getPortSilently }?: PreviewServerOptions): Promise<StartServerResult>;
25
25
  export {};
@@ -36,6 +36,7 @@ var import_connect = __toESM(require("@rsbuild/shared/connect"));
36
36
  var import_path = require("path");
37
37
  var import_sirv = __toESM(require("../../compiled/sirv"));
38
38
  var import_shared = require("@rsbuild/shared");
39
+ var import_helper = require("./helper");
39
40
  var import_middlewares = require("./middlewares");
40
41
  var import_httpServer = require("./httpServer");
41
42
  class RsbuildProdServer {
@@ -118,7 +119,7 @@ async function startProdServer(context, rsbuildConfig, { printURLs = true, getPo
118
119
  if (!process.env.NODE_ENV) {
119
120
  process.env.NODE_ENV = "production";
120
121
  }
121
- const { serverConfig, port, host, https } = await (0, import_shared.getServerOptions)({
122
+ const { serverConfig, port, host, https } = await (0, import_helper.getServerOptions)({
122
123
  rsbuildConfig,
123
124
  getPortSilently
124
125
  });
@@ -143,7 +144,7 @@ async function startProdServer(context, rsbuildConfig, { printURLs = true, getPo
143
144
  port
144
145
  },
145
146
  async () => {
146
- const routes = (0, import_shared.formatRoutes)(
147
+ const routes = (0, import_helper.formatRoutes)(
147
148
  context.entry,
148
149
  rsbuildConfig.output?.distPath?.html,
149
150
  rsbuildConfig.html?.outputStructure
@@ -154,7 +155,7 @@ async function startProdServer(context, rsbuildConfig, { printURLs = true, getPo
154
155
  });
155
156
  const urls = (0, import_shared.getAddressUrls)(https ? "https" : "http", port);
156
157
  if (printURLs) {
157
- (0, import_shared.printServerURLs)(
158
+ (0, import_helper.printServerURLs)(
158
159
  (0, import_shared.isFunction)(printURLs) ? printURLs(urls) : urls,
159
160
  routes
160
161
  );
@@ -110,7 +110,7 @@ class SocketServer {
110
110
  this.sockets.splice(idx, 1);
111
111
  }
112
112
  });
113
- if (this.options.hmr) {
113
+ if (this.options.hmr || this.options.liveReload) {
114
114
  this.singleWrite(connection, "hot");
115
115
  }
116
116
  if (this.stats) {
package/dist/types.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import type { Context as BaseContext, RsbuildConfig, RsbuildPlugin, NormalizedConfig, RsbuildPluginAPI } from '@rsbuild/shared';
1
+ import type { RsbuildConfig, RsbuildPlugin, RsbuildContext, NormalizedConfig, RsbuildPluginAPI } from '@rsbuild/shared';
2
2
  import type { Hooks } from './provider/core/initHooks';
3
3
  export type { RsbuildPlugin, RsbuildPluginAPI };
4
4
  /** The inner context. */
5
- export type Context = BaseContext & {
5
+ export type InternalContext = RsbuildContext & {
6
6
  /** All hooks. */
7
7
  hooks: Readonly<Hooks>;
8
8
  /** Current Rsbuild config. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.2.10",
3
+ "version": "0.2.12",
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": {
@@ -56,11 +56,11 @@
56
56
  "types.d.ts"
57
57
  ],
58
58
  "dependencies": {
59
- "@rspack/core": "0.4.4",
59
+ "@rspack/core": "0.4.5",
60
60
  "core-js": "~3.32.2",
61
61
  "html-webpack-plugin": "npm:html-rspack-plugin@5.5.7",
62
62
  "postcss": "8.4.31",
63
- "@rsbuild/shared": "0.2.10"
63
+ "@rsbuild/shared": "0.2.12"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@types/node": "16.x",