@rsbuild/core 0.3.3 → 0.3.5

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.
@@ -1 +1 @@
1
- (()=>{"use strict";var e={509:(e,t,r)=>{const n=r(796);const s=/text|javascript|\/json|xml/i;const noop=()=>{};const getChunkSize=(e,t)=>e?Buffer.byteLength(e,t):0;e.exports=({threshold:e=1024,level:t=-1,brotli:r=true,gzip:i=true,mimes:o=s}={})=>{const a=typeof r==="object"&&r||{};const c=typeof i==="object"&&i||{};if(r&&!n.createBrotliCompress)r=false;return(s,l,p=noop)=>{const f=s.headers["accept-encoding"];const u=f&&(r&&f.match(/\bbr\b/)||i&&f.match(/\bgzip\b/)||[])[0];if(s.method==="HEAD"||!u)return p();let _;let d;let b=[];let h=false;let g=0;function start(){h=true;g=l.getHeader("Content-Length")|0||g;const r=o.test(String(l.getHeader("Content-Type")||"text/plain"));const s=!l.getHeader("Content-Encoding");const i=b||[];if(r&&s&&g>=e){l.setHeader("Content-Encoding",u);l.removeHeader("Content-Length");if(u==="br"){const e={[n.constants.BROTLI_PARAM_QUALITY]:t,[n.constants.BROTLI_PARAM_SIZE_HINT]:g};_=n.createBrotliCompress({params:Object.assign(e,a)})}else{_=n.createGzip(Object.assign({level:t},c))}_.on("data",(e=>m.call(l,e)===false&&_.pause()));v.call(l,"drain",(()=>_.resume()));_.on("end",(()=>y.call(l)));i.forEach((e=>_.on.apply(_,e)))}else{b=null;i.forEach((e=>v.apply(l,e)))}w.call(l,d||l.statusCode)}const{end:y,write:m,on:v,writeHead:w}=l;l.writeHead=function(e,t,r){if(typeof t!=="string")[r,t]=[t,r];if(r)for(const e in r)l.setHeader(e,r[e]);d=e;return this};l.write=function(e,t){g+=getChunkSize(e,t);if(!h)start();if(!_)return m.apply(this,arguments);return _.write.apply(_,arguments)};l.end=function(e,t){if(arguments.length>0&&typeof e!=="function"){g+=getChunkSize(e,t)}if(!h)start();if(!_)return y.apply(this,arguments);return _.end.apply(_,arguments)};l.on=function(e,t){if(!b||e!=="drain")v.call(this,e,t);else if(_)_.on(e,t);else b.push([e,t]);return this};p()}}},796:e=>{e.exports=require("zlib")}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var s=t[r]={exports:{}};var i=true;try{e[r](s,s.exports,__nccwpck_require__);i=false}finally{if(i)delete t[r]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(509);module.exports=r})();
1
+ (()=>{"use strict";var e={654:(e,t,r)=>{const n=r(796);const i=/text|javascript|\/json|xml/i;const noop=()=>{};const getChunkSize=(e,t)=>e?Buffer.byteLength(e,t):0;e.exports=({threshold:e=1024,level:t=-1,brotli:r=true,gzip:s=true,mimes:a=i}={})=>{const o=typeof r==="object"&&r||{};const c=typeof s==="object"&&s||{};if(r&&!n.createBrotliCompress)r=false;return(i,l,p=noop)=>{const f=i.headers["accept-encoding"];const u=f&&(r&&f.match(/\bbr\b/)||s&&f.match(/\bgzip\b/)||[])[0];if(i.method==="HEAD"||!u)return p();let _;let d;let b=[];let h=false;let g=0;function start(){h=true;g=l.getHeader("Content-Length")|0||g;const r=a.test(String(l.getHeader("Content-Type")||"text/plain"));const i=!l.getHeader("Content-Encoding");const s=b||[];if(r&&i&&g>=e){l.setHeader("Content-Encoding",u);l.removeHeader("Content-Length");if(u==="br"){_=n.createBrotliCompress({params:Object.assign({[n.constants.BROTLI_PARAM_QUALITY]:t===-1?1:t,[n.constants.BROTLI_PARAM_SIZE_HINT]:g},o)})}else{_=n.createGzip(Object.assign({level:t===-1?7:t},c))}_.on("data",(e=>m.call(l,e)===false&&_.pause()));v.call(l,"drain",(()=>_.resume()));_.on("end",(()=>y.call(l)));s.forEach((e=>_.on.apply(_,e)))}else{b=null;s.forEach((e=>v.apply(l,e)))}w.call(l,d||l.statusCode)}const{end:y,write:m,on:v,writeHead:w}=l;l.writeHead=function(e,t,r){if(typeof t!=="string")[r,t]=[t,r];if(r)for(const e in r)l.setHeader(e,r[e]);d=e;return this};l.write=function(e,t){g+=getChunkSize(e,t);if(!h)start();if(!_)return m.apply(this,arguments);return _.write.apply(_,arguments)};l.end=function(e,t){if(arguments.length>0&&typeof e!=="function"){g+=getChunkSize(e,t)}if(!h)start();if(!_)return y.apply(this,arguments);return _.end.apply(_,arguments)};l.on=function(e,t){if(!b||e!=="drain")v.call(this,e,t);else if(_)_.on(e,t);else b.push([e,t]);return this};p()}}},796:e=>{e.exports=require("zlib")}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var i=t[r]={exports:{}};var s=true;try{e[r](i,i.exports,__nccwpck_require__);s=false}finally{if(s)delete t[r]}return i.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r=__nccwpck_require__(654);module.exports=r})();
@@ -1 +1 @@
1
- {"name":"http-compression","author":{"email":"josefrancisco.verdu@gmail.com","name":"Kiko Beats","url":"https://kikobeats.com"},"version":"1.0.6","license":"MIT","types":"index.d.ts","type":"commonjs"}
1
+ {"name":"http-compression","author":{"email":"josefrancisco.verdu@gmail.com","name":"Kiko Beats","url":"https://kikobeats.com"},"version":"1.0.17","license":"MIT","types":"index.d.ts","type":"commonjs"}
@@ -0,0 +1 @@
1
+ export = any;
@@ -0,0 +1 @@
1
+ (()=>{"use strict";var e={950:(e,r,t)=>{const n=t(867);e.exports=n.default;e.exports.raw=n.raw},867:(e,r,t)=>{Object.defineProperty(r,"__esModule",{value:true});r["default"]=loader;r.raw=void 0;var n=t(72);var o=_interopRequireDefault(t(349));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function loader(e){const r=this.getOptions(o.default);const t=(0,n.interpolateName)(this,typeof r.name!=="undefined"?r.name:"[contenthash].[ext]",{context:this.rootContext,content:e});this.emitFile(t,e);return`\ntry {\n process.dlopen(module, __dirname + require("path").sep + __webpack_public_path__ + ${JSON.stringify(t)}${typeof r.flags!=="undefined"?`, ${JSON.stringify(r.flags)}`:""});\n} catch (error) {\n throw new Error('node-loader:\\n' + error);\n}\n`}const a=true;r.raw=a},72:e=>{e.exports=require("@rsbuild/shared/loader-utils2")},349:e=>{e.exports=JSON.parse('{"title":"Node Loader options","type":"object","properties":{"name":{"anyOf":[{"type":"string"},{"instanceof":"Function"}]},"flags":{"type":"integer"}},"additionalProperties":false}')}};var r={};function __nccwpck_require__(t){var n=r[t];if(n!==undefined){return n.exports}var o=r[t]={exports:{}};var a=true;try{e[t](o,o.exports,__nccwpck_require__);a=false}finally{if(a)delete r[t]}return o.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var t=__nccwpck_require__(950);module.exports=t})();
@@ -0,0 +1,20 @@
1
+ Copyright JS Foundation and other contributors
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ 'Software'), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ {"name":"node-loader","author":"Tobias Koppers @sokra","version":"2.0.0","funding":{"type":"opencollective","url":"https://opencollective.com/webpack"},"license":"MIT","types":"index.d.ts","type":"commonjs"}
@@ -1,6 +1,7 @@
1
1
  import type { RsbuildMode } from '..';
2
2
  export type CommonOptions = {
3
3
  config?: string;
4
+ envMode?: string;
4
5
  open?: boolean | string;
5
6
  host?: string;
6
7
  port?: number;
@@ -49,12 +49,25 @@ async function init({
49
49
  }
50
50
  try {
51
51
  const root = process.cwd();
52
- const envs = (0, import_loadEnv.loadEnv)({ cwd: root });
53
- (0, import_shared.isDev)() && (0, import_restart.onBeforeRestartServer)(envs.cleanup);
54
- const config = await (0, import_config.loadConfig)({
52
+ const envs = (0, import_loadEnv.loadEnv)({
53
+ cwd: root,
54
+ mode: cliOptions?.envMode
55
+ });
56
+ if ((0, import_shared.isDev)()) {
57
+ (0, import_restart.onBeforeRestartServer)(envs.cleanup);
58
+ }
59
+ const { content: config, filePath: configFilePath } = await (0, import_config.loadConfigV2)({
55
60
  cwd: root,
56
61
  path: commonOpts.config
57
62
  });
63
+ const command = process.argv[2];
64
+ if (command === "dev") {
65
+ const files = [...envs.filePaths];
66
+ if (configFilePath) {
67
+ files.push(configFilePath);
68
+ }
69
+ (0, import_config.watchFiles)(files);
70
+ }
58
71
  const { createRsbuild } = await Promise.resolve().then(() => __toESM(require("../createRsbuild")));
59
72
  config.source || (config.source = {});
60
73
  config.source.define = {
@@ -85,18 +98,29 @@ async function init({
85
98
  }
86
99
  }
87
100
  }
88
- function runCli() {
89
- import_commander.program.name("rsbuild").usage("<command> [options]").version("0.3.3");
90
- import_commander.program.command("dev").option("-o --open [url]", "open the page in browser on startup").option(
91
- "--port <port>",
92
- "specify a port number for Rsbuild Server to listen"
93
- ).option(
94
- "--host <host>",
95
- "specify the host that the Rsbuild Server listens to"
96
- ).option(
101
+ const applyCommonOptions = (command) => {
102
+ command.option(
97
103
  "-c --config <config>",
98
104
  "specify the configuration file, can be a relative or absolute path"
99
- ).description("starting the dev server").action(async (options) => {
105
+ ).option(
106
+ "--env-mode <mode>",
107
+ "specify the env mode to load the `.env.[mode]` file"
108
+ );
109
+ };
110
+ const applyServerOptions = (command) => {
111
+ command.option("-o --open [url]", "open the page in browser on startup").option("--port <port>", "specify a port number for server to listen").option("--host <host>", "specify the host that the server listens to");
112
+ };
113
+ function runCli() {
114
+ import_commander.program.name("rsbuild").usage("<command> [options]").version("0.3.5");
115
+ const devCommand = import_commander.program.command("dev");
116
+ const buildCommand = import_commander.program.command("build");
117
+ const previewCommand = import_commander.program.command("preview");
118
+ const inspectCommand = import_commander.program.command("inspect");
119
+ [devCommand, buildCommand, previewCommand, inspectCommand].forEach(
120
+ applyCommonOptions
121
+ );
122
+ [devCommand, previewCommand].forEach(applyServerOptions);
123
+ devCommand.description("starting the dev server").action(async (options) => {
100
124
  try {
101
125
  const rsbuild = await init({ cliOptions: options });
102
126
  await rsbuild?.startDevServer();
@@ -106,10 +130,7 @@ function runCli() {
106
130
  process.exit(1);
107
131
  }
108
132
  });
109
- import_commander.program.command("build").option("-w --watch", "turn on watch mode, watch for changes and rebuild").option(
110
- "-c --config <config>",
111
- "specify the configuration file, can be a relative or absolute path"
112
- ).description("build the app for production").action(async (options) => {
133
+ buildCommand.option("-w --watch", "turn on watch mode, watch for changes and rebuild").description("build the app for production").action(async (options) => {
113
134
  try {
114
135
  const rsbuild = await init({ cliOptions: options });
115
136
  await rsbuild?.build({
@@ -121,16 +142,7 @@ function runCli() {
121
142
  process.exit(1);
122
143
  }
123
144
  });
124
- import_commander.program.command("preview").option("-o --open [url]", "open the page in browser on startup").option(
125
- "--port <port>",
126
- "specify a port number for Rsbuild Server to listen"
127
- ).option(
128
- "--host <host>",
129
- "specify the host that the Rsbuild Server listens to"
130
- ).option(
131
- "-c --config <config>",
132
- "specify the configuration file, can be a relative or absolute path"
133
- ).description("preview the production build locally").action(async (options) => {
145
+ previewCommand.description("preview the production build locally").action(async (options) => {
134
146
  try {
135
147
  const rsbuild = await init({ cliOptions: options });
136
148
  if (rsbuild && !(0, import_fs.existsSync)(rsbuild.context.distPath)) {
@@ -147,10 +159,7 @@ function runCli() {
147
159
  process.exit(1);
148
160
  }
149
161
  });
150
- import_commander.program.command("inspect").description("inspect the Rspack and Rsbuild configs").option("--env <env>", "specify env mode", "development").option("--output <output>", "specify inspect content output path", "/").option("--verbose", "show full function definitions in output").option(
151
- "-c --config <config>",
152
- "specify the configuration file, can be a relative or absolute path"
153
- ).action(async (options) => {
162
+ inspectCommand.description("inspect the Rspack and Rsbuild configs").option("--env <env>", "specify env mode", "development").option("--output <output>", "specify inspect content output path", "/").option("--verbose", "show full function definitions in output").action(async (options) => {
154
163
  try {
155
164
  const rsbuild = await init({ cliOptions: options });
156
165
  await rsbuild?.inspectConfig({
@@ -14,7 +14,16 @@ export declare function defineConfig(config: RsbuildConfig): RsbuildConfig;
14
14
  export declare function defineConfig(config: RsbuildConfigSyncFn): RsbuildConfigSyncFn;
15
15
  export declare function defineConfig(config: RsbuildConfigAsyncFn): RsbuildConfigAsyncFn;
16
16
  export declare function defineConfig(config: RsbuildConfigExport): RsbuildConfigExport;
17
+ export declare function watchFiles(files: string[]): Promise<void>;
18
+ export declare function loadConfigByPath(configFile: string): Promise<RsbuildConfig>;
17
19
  export declare function loadConfig({ cwd, path, }: {
18
20
  cwd: string;
19
21
  path?: string;
20
22
  }): Promise<RsbuildConfig>;
23
+ export declare function loadConfigV2({ cwd, path, }: {
24
+ cwd: string;
25
+ path?: string;
26
+ }): Promise<{
27
+ content: RsbuildConfig;
28
+ filePath: string | null;
29
+ }>;
@@ -29,13 +29,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
29
29
  var config_exports = {};
30
30
  __export(config_exports, {
31
31
  defineConfig: () => defineConfig,
32
- loadConfig: () => loadConfig
32
+ loadConfig: () => loadConfig,
33
+ loadConfigByPath: () => loadConfigByPath,
34
+ loadConfigV2: () => loadConfigV2,
35
+ watchFiles: () => watchFiles
33
36
  });
34
37
  module.exports = __toCommonJS(config_exports);
35
38
  var import_fs = __toESM(require("fs"));
36
39
  var import_path = require("path");
37
40
  var import_shared = require("@rsbuild/shared");
38
- var import_loadEnv = require("../loadEnv");
39
41
  var import_restart = require("../server/restart");
40
42
  function defineConfig(config) {
41
43
  return config;
@@ -65,10 +67,12 @@ const resolveConfigPath = (root, customConfig) => {
65
67
  }
66
68
  return null;
67
69
  };
68
- async function watchConfig(root, configFile) {
70
+ async function watchFiles(files) {
71
+ if (!files.length) {
72
+ return;
73
+ }
69
74
  const chokidar = await Promise.resolve().then(() => __toESM(require("@rsbuild/shared/chokidar")));
70
- const envFiles = (0, import_loadEnv.getEnvFiles)().map((filename) => (0, import_path.join)(root, filename));
71
- const watcher = chokidar.watch([configFile, ...envFiles], {
75
+ const watcher = chokidar.watch(files, {
72
76
  // do not trigger add for initial files
73
77
  ignoreInitial: true,
74
78
  // If watching fails due to read permissions, the errors will be suppressed silently.
@@ -86,14 +90,7 @@ async function watchConfig(root, configFile) {
86
90
  watcher.on("change", callback);
87
91
  watcher.on("unlink", callback);
88
92
  }
89
- async function loadConfig({
90
- cwd,
91
- path
92
- }) {
93
- const configFile = resolveConfigPath(cwd, path);
94
- if (!configFile) {
95
- return {};
96
- }
93
+ async function loadConfigByPath(configFile) {
97
94
  try {
98
95
  const { default: jiti } = await Promise.resolve().then(() => __toESM(require("@rsbuild/shared/jiti")));
99
96
  const loadConfig2 = jiti(__filename, {
@@ -102,14 +99,11 @@ async function loadConfig({
102
99
  requireCache: false,
103
100
  interopDefault: true
104
101
  });
105
- const command = process.argv[2];
106
- if (command === "dev") {
107
- watchConfig(cwd, configFile);
108
- }
109
102
  const configExport = loadConfig2(configFile);
110
103
  if (typeof configExport === "function") {
104
+ const command = process.argv[2];
111
105
  const params = {
112
- env: process.env.NODE_ENV,
106
+ env: (0, import_shared.getNodeEnv)(),
113
107
  command
114
108
  };
115
109
  const result = await configExport(params);
@@ -124,8 +118,37 @@ async function loadConfig({
124
118
  throw err;
125
119
  }
126
120
  }
121
+ async function loadConfig({
122
+ cwd,
123
+ path
124
+ }) {
125
+ const configFile = resolveConfigPath(cwd, path);
126
+ if (!configFile) {
127
+ return {};
128
+ }
129
+ return loadConfigByPath(configFile);
130
+ }
131
+ async function loadConfigV2({
132
+ cwd,
133
+ path
134
+ }) {
135
+ const configFile = resolveConfigPath(cwd, path);
136
+ if (!configFile) {
137
+ return {
138
+ content: {},
139
+ filePath: configFile
140
+ };
141
+ }
142
+ return {
143
+ content: await loadConfigByPath(configFile),
144
+ filePath: configFile
145
+ };
146
+ }
127
147
  // Annotate the CommonJS export names for ESM import in node:
128
148
  0 && (module.exports = {
129
149
  defineConfig,
130
- loadConfig
150
+ loadConfig,
151
+ loadConfigByPath,
152
+ loadConfigV2,
153
+ watchFiles
131
154
  });
@@ -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.3.3"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.3.5"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
@@ -366,11 +366,14 @@ function canApplyUpdates() {
366
366
  return module.hot.status() === "idle";
367
367
  }
368
368
  function tryApplyUpdates() {
369
+ if (!isUpdateAvailable()) {
370
+ return;
371
+ }
369
372
  if (!module.hot) {
370
373
  window.location.reload();
371
374
  return;
372
375
  }
373
- if (!isUpdateAvailable() || !canApplyUpdates()) {
376
+ if (!canApplyUpdates()) {
374
377
  return;
375
378
  }
376
379
  function handleApplyUpdates(err, updatedModules) {
package/dist/index.js CHANGED
@@ -38,7 +38,7 @@ var import_createRsbuild = require("./createRsbuild");
38
38
  var import_config = require("./cli/config");
39
39
  var import_shared = require("@rsbuild/shared");
40
40
  var import_constants = require("./constants");
41
- const version = "0.3.3";
41
+ const version = "0.3.5";
42
42
  // Annotate the CommonJS export names for ESM import in node:
43
43
  0 && (module.exports = {
44
44
  PLUGIN_BABEL_NAME,
package/dist/loadEnv.d.ts CHANGED
@@ -1,9 +1,27 @@
1
- export declare const getEnvFiles: () => string[];
2
- export declare function loadEnv({ cwd, prefixes, }?: {
1
+ export type LoadEnvOptions = {
2
+ /**
3
+ * The root path to load the env file
4
+ * @default process.cwd()
5
+ */
3
6
  cwd?: string;
7
+ /**
8
+ * Used to specify the name of the .env.[mode] file
9
+ * @default process.env.NODE_ENV
10
+ */
11
+ mode?: string;
12
+ /**
13
+ * The prefix of public variables
14
+ * @default ['PUBLIC_']
15
+ */
4
16
  prefixes?: string[];
5
- }): {
17
+ };
18
+ export declare function loadEnv({ cwd, mode, prefixes, }?: LoadEnvOptions): {
19
+ /** All environment variables in the .env file */
6
20
  parsed: Record<string, string>;
21
+ /** The absolute paths to all env files */
22
+ filePaths: string[];
23
+ /** Environment variables that start with prefixes */
7
24
  publicVars: Record<string, string>;
25
+ /** Clear the environment variables mounted on `process.env` */
8
26
  cleanup: () => void;
9
27
  };
package/dist/loadEnv.js CHANGED
@@ -28,7 +28,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
  var loadEnv_exports = {};
30
30
  __export(loadEnv_exports, {
31
- getEnvFiles: () => getEnvFiles,
32
31
  loadEnv: () => loadEnv
33
32
  });
34
33
  module.exports = __toCommonJS(loadEnv_exports);
@@ -37,17 +36,20 @@ var import_path = require("path");
37
36
  var import_shared = require("@rsbuild/shared");
38
37
  var import_dotenv = require("../compiled/dotenv");
39
38
  var import_dotenv_expand = require("../compiled/dotenv-expand");
40
- const getEnvFiles = () => {
41
- const { NODE_ENV } = process.env;
42
- return [".env", ".env.local", `.env.${NODE_ENV}`, `.env.${NODE_ENV}.local`];
43
- };
44
39
  function loadEnv({
45
40
  cwd = process.cwd(),
41
+ mode = (0, import_shared.getNodeEnv)(),
46
42
  prefixes = ["PUBLIC_"]
47
43
  } = {}) {
48
- const envPaths = getEnvFiles().map((filename) => (0, import_path.join)(cwd, filename)).filter(import_shared.isFileSync);
44
+ const filenames = [
45
+ ".env",
46
+ ".env.local",
47
+ `.env.${mode}`,
48
+ `.env.${mode}.local`
49
+ ];
50
+ const filePaths = filenames.map((filename) => (0, import_path.join)(cwd, filename)).filter(import_shared.isFileSync);
49
51
  const parsed = {};
50
- envPaths.forEach((envPath) => {
52
+ filePaths.forEach((envPath) => {
51
53
  Object.assign(parsed, (0, import_dotenv.parse)(import_fs.default.readFileSync(envPath)));
52
54
  });
53
55
  (0, import_dotenv_expand.expand)({ parsed });
@@ -71,12 +73,12 @@ function loadEnv({
71
73
  };
72
74
  return {
73
75
  parsed,
74
- publicVars,
75
- cleanup
76
+ cleanup,
77
+ filePaths,
78
+ publicVars
76
79
  };
77
80
  }
78
81
  // Annotate the CommonJS export names for ESM import in node:
79
82
  0 && (module.exports = {
80
- getEnvFiles,
81
83
  loadEnv
82
84
  });
@@ -30,7 +30,7 @@ const pluginDefine = () => ({
30
30
  const publicPath = chain.output.get("publicPath");
31
31
  const assetPrefix = publicPath && typeof publicPath === "string" ? publicPath : config.output.assetPrefix;
32
32
  const builtinVars = {
33
- "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
33
+ "process.env.NODE_ENV": JSON.stringify((0, import_shared.getNodeEnv)()),
34
34
  "process.env.ASSET_PREFIX": JSON.stringify(
35
35
  (0, import_shared.removeTailSlash)(assetPrefix)
36
36
  )
@@ -51,12 +51,12 @@ const pluginNodeAddons = () => ({
51
51
  }
52
52
  return `${filename}`;
53
53
  };
54
- const { name: pkgName } = require(pkgJSON);
54
+ const { name: pkgName } = import_shared.fse.readJSONSync(pkgJSON);
55
55
  const config = api.getNormalizedConfig();
56
56
  const serverPath = (0, import_shared.getDistPath)(config, "server");
57
57
  return `${serverPath}/${getFilename(resourcePath, pkgName)}`;
58
58
  };
59
- chain.module.rule(CHAIN_ID.RULE.NODE).test(/\.node$/).use(CHAIN_ID.USE.NODE).loader((0, import_shared.getSharedPkgCompiledPath)("node-loader")).options({
59
+ chain.module.rule(CHAIN_ID.RULE.NODE).test(/\.node$/).use(CHAIN_ID.USE.NODE).loader((0, import_path.join)(__dirname, "../../compiled/node-loader")).options({
60
60
  name: getDistName
61
61
  });
62
62
  });
@@ -37,10 +37,18 @@ const pluginServer = () => ({
37
37
  if (!import_shared.fse.existsSync(publicDir)) {
38
38
  return;
39
39
  }
40
- await import_shared.fse.copy(publicDir, api.context.distPath, {
41
- // dereference symlinks
42
- dereference: true
43
- });
40
+ try {
41
+ await import_shared.fse.copy(publicDir, api.context.distPath, {
42
+ // dereference symlinks
43
+ dereference: true
44
+ });
45
+ } catch (err) {
46
+ if (err instanceof Error) {
47
+ err.message = `Copy public dir (${publicDir}) to dist failed:
48
+ ${err.message}`;
49
+ }
50
+ throw err;
51
+ }
44
52
  }
45
53
  });
46
54
  }
@@ -72,9 +72,9 @@ async function openBrowser(url) {
72
72
  );
73
73
  return true;
74
74
  }
75
- import_shared.logger.debug("Failed to find the target browser.");
75
+ (0, import_shared.debug)("Failed to find the target browser.");
76
76
  } catch (err) {
77
- import_shared.logger.debug("Failed to open start URL with apple script.");
77
+ (0, import_shared.debug)("Failed to open start URL with apple script.");
78
78
  import_shared.logger.debug(err);
79
79
  }
80
80
  }
@@ -107,11 +107,7 @@ function pluginStartUrl() {
107
107
  if (startUrl === true || !startUrl) {
108
108
  const protocol = https ? "https" : "http";
109
109
  if (routes.length) {
110
- urls.push(
111
- (0, import_shared.normalizeUrl)(
112
- `${protocol}://localhost:${port}/${routes[0].route}`
113
- )
114
- );
110
+ urls.push(`${protocol}://localhost:${port}${routes[0].pathname}`);
115
111
  }
116
112
  } else {
117
113
  urls.push(
@@ -1,6 +1,5 @@
1
1
  import { type RsbuildConfig, type NormalizedConfig } from '@rsbuild/shared';
2
- export declare const createDefaultConfig: () => RsbuildConfig;
3
- export declare const withDefaultConfig: (config: RsbuildConfig) => RsbuildConfig;
2
+ export declare const withDefaultConfig: (rootPath: string, config: RsbuildConfig) => Promise<RsbuildConfig>;
4
3
  /** #__PURE__
5
4
  * 1. May used by multiple plugins.
6
5
  * 2. Object value that should not be empty.
@@ -18,11 +18,11 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var config_exports = {};
20
20
  __export(config_exports, {
21
- createDefaultConfig: () => createDefaultConfig,
22
21
  normalizeConfig: () => normalizeConfig,
23
22
  withDefaultConfig: () => withDefaultConfig
24
23
  });
25
24
  module.exports = __toCommonJS(config_exports);
25
+ var import_path = require("path");
26
26
  var import_shared = require("@rsbuild/shared");
27
27
  const createDefaultConfig = () => ({
28
28
  dev: (0, import_shared.getDefaultDevConfig)(),
@@ -34,14 +34,48 @@ const createDefaultConfig = () => ({
34
34
  security: (0, import_shared.getDefaultSecurityConfig)(),
35
35
  performance: (0, import_shared.getDefaultPerformanceConfig)()
36
36
  });
37
- const withDefaultConfig = (config) => (0, import_shared.mergeRsbuildConfig)(createDefaultConfig(), config);
37
+ function getDefaultEntry(root) {
38
+ const files = [
39
+ // Most projects are using typescript now.
40
+ // So we put `.ts` as the first one to improve performance.
41
+ "ts",
42
+ "js",
43
+ "tsx",
44
+ "jsx",
45
+ ".mjs",
46
+ ".cjs"
47
+ ].map((ext) => (0, import_path.join)(root, `src/index.${ext}`));
48
+ const entryFile = (0, import_shared.findExists)(files);
49
+ if (entryFile) {
50
+ return {
51
+ index: entryFile
52
+ };
53
+ }
54
+ return {};
55
+ }
56
+ const withDefaultConfig = async (rootPath, config) => {
57
+ const merged = (0, import_shared.mergeRsbuildConfig)(
58
+ createDefaultConfig(),
59
+ config
60
+ );
61
+ merged.source || (merged.source = {});
62
+ if (!merged.source.entry) {
63
+ merged.source.entry = getDefaultEntry(rootPath);
64
+ }
65
+ if (!merged.source.tsconfigPath) {
66
+ const tsconfigPath = (0, import_path.join)(rootPath, import_shared.TS_CONFIG_FILE);
67
+ if (await (0, import_shared.isFileExists)(tsconfigPath)) {
68
+ merged.source.tsconfigPath = tsconfigPath;
69
+ }
70
+ }
71
+ return merged;
72
+ };
38
73
  const normalizeConfig = (config) => (0, import_shared.mergeRsbuildConfig)(
39
74
  createDefaultConfig(),
40
75
  config
41
76
  );
42
77
  // Annotate the CommonJS export names for ESM import in node:
43
78
  0 && (module.exports = {
44
- createDefaultConfig,
45
79
  normalizeConfig,
46
80
  withDefaultConfig
47
81
  });
@@ -25,8 +25,8 @@ var import_createCompiler = require("./createCompiler");
25
25
  var import_initConfigs = require("./initConfigs");
26
26
  var import_shared = require("@rsbuild/shared");
27
27
  const build = async (initOptions, { mode = "production", watch, compiler: customCompiler } = {}) => {
28
- if (!process.env.NODE_ENV) {
29
- process.env.NODE_ENV = mode;
28
+ if (!(0, import_shared.getNodeEnv)()) {
29
+ (0, import_shared.setNodeEnv)(mode);
30
30
  }
31
31
  const { context } = initOptions;
32
32
  let compiler;
@@ -57,7 +57,7 @@ async function createCompiler({
57
57
  let isCompiling = false;
58
58
  const logRspackVersion = () => {
59
59
  if (!isVersionLogged) {
60
- import_shared.logger.debug(`Use Rspack v${rspack.rspackVersion}`);
60
+ (0, import_shared.debug)(`Use Rspack v${rspack.rspackVersion}`);
61
61
  isVersionLogged = true;
62
62
  }
63
63
  };
@@ -1,9 +1,5 @@
1
1
  import { type BundlerType, type RsbuildConfig, type RsbuildContext, type NormalizedConfig, type CreateRsbuildOptions } from '@rsbuild/shared';
2
2
  import type { InternalContext } from '../../types';
3
- /**
4
- * Create context by config.
5
- */
6
- export declare function createContextByConfig(options: Required<CreateRsbuildOptions>, bundlerType: BundlerType, config?: RsbuildConfig): RsbuildContext;
7
3
  export declare function updateContextByNormalizedConfig(context: RsbuildContext, config: NormalizedConfig): void;
8
4
  export declare function createPublicContext(context: RsbuildContext): Readonly<RsbuildContext>;
9
5
  /**
@@ -19,7 +19,6 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var createContext_exports = {};
20
20
  __export(createContext_exports, {
21
21
  createContext: () => createContext,
22
- createContextByConfig: () => createContextByConfig,
23
22
  createPublicContext: () => createPublicContext,
24
23
  updateContextByNormalizedConfig: () => updateContextByNormalizedConfig
25
24
  });
@@ -28,42 +27,28 @@ var import_path = require("path");
28
27
  var import_shared = require("@rsbuild/shared");
29
28
  var import_initHooks = require("./initHooks");
30
29
  var import_config = require("../config");
31
- function getDefaultEntry(root) {
32
- const files = [
33
- // Most projects are using typescript now.
34
- // So we put `.ts` as the first one to improve performance.
35
- "ts",
36
- "js",
37
- "tsx",
38
- "jsx",
39
- ".mjs",
40
- ".cjs"
41
- ].map((ext) => (0, import_path.join)(root, `src/index.${ext}`));
42
- const entryFile = (0, import_shared.findExists)(files);
43
- if (entryFile) {
44
- return {
45
- index: entryFile
46
- };
47
- }
48
- return {};
30
+ function getAbsolutePath(root, filepath) {
31
+ return (0, import_path.isAbsolute)(filepath) ? filepath : (0, import_path.join)(root, filepath);
49
32
  }
50
33
  function getAbsoluteDistPath(cwd, config) {
51
- const root = (0, import_shared.getDistPath)(config, "root");
52
- return (0, import_path.isAbsolute)(root) ? root : (0, import_path.join)(cwd, root);
34
+ const dirRoot = (0, import_shared.getDistPath)(config, "root");
35
+ return getAbsolutePath(cwd, dirRoot);
53
36
  }
54
- function createContextByConfig(options, bundlerType, config = {}) {
37
+ async function createContextByConfig(options, bundlerType, config = {}) {
55
38
  const { cwd } = options;
56
39
  const rootPath = cwd;
57
40
  const distPath = getAbsoluteDistPath(cwd, config);
58
41
  const cachePath = (0, import_path.join)(rootPath, "node_modules", ".cache");
42
+ const tsconfigPath = config.source?.tsconfigPath;
59
43
  const context = {
60
- entry: config.source?.entry || getDefaultEntry(rootPath),
44
+ entry: config.source?.entry || {},
61
45
  targets: config.output?.targets || [],
62
- version: "0.3.3",
46
+ version: "0.3.5",
63
47
  rootPath,
64
48
  distPath,
65
49
  cachePath,
66
- bundlerType
50
+ bundlerType,
51
+ tsconfigPath: tsconfigPath ? getAbsolutePath(rootPath, tsconfigPath) : void 0
67
52
  };
68
53
  return context;
69
54
  }
@@ -73,6 +58,12 @@ function updateContextByNormalizedConfig(context, config) {
73
58
  if (config.source.entry) {
74
59
  context.entry = config.source.entry;
75
60
  }
61
+ if (config.source.tsconfigPath) {
62
+ context.tsconfigPath = getAbsolutePath(
63
+ context.rootPath,
64
+ config.source.tsconfigPath
65
+ );
66
+ }
76
67
  }
77
68
  function createPublicContext(context) {
78
69
  const exposedKeys = [
@@ -103,21 +94,22 @@ function createPublicContext(context) {
103
94
  });
104
95
  }
105
96
  async function createContext(options, userRsbuildConfig, bundlerType) {
106
- const rsbuildConfig = (0, import_config.withDefaultConfig)(userRsbuildConfig);
107
- const context = createContextByConfig(options, bundlerType, rsbuildConfig);
108
- const tsconfigPath = (0, import_path.join)(context.rootPath, import_shared.TS_CONFIG_FILE);
97
+ const rsbuildConfig = await (0, import_config.withDefaultConfig)(options.cwd, userRsbuildConfig);
98
+ const context = await createContextByConfig(
99
+ options,
100
+ bundlerType,
101
+ rsbuildConfig
102
+ );
109
103
  return {
110
104
  ...context,
111
105
  hooks: (0, import_initHooks.initHooks)(),
112
106
  config: { ...rsbuildConfig },
113
- originalConfig: userRsbuildConfig,
114
- tsconfigPath: await (0, import_shared.isFileExists)(tsconfigPath) ? tsconfigPath : void 0
107
+ originalConfig: userRsbuildConfig
115
108
  };
116
109
  }
117
110
  // Annotate the CommonJS export names for ESM import in node:
118
111
  0 && (module.exports = {
119
112
  createContext,
120
- createContextByConfig,
121
113
  createPublicContext,
122
114
  updateContextByNormalizedConfig
123
115
  });
@@ -77,7 +77,7 @@ async function initConfigs({
77
77
  });
78
78
  };
79
79
  context.hooks.onBeforeBuild.tap(inspect);
80
- context.hooks.onBeforeStartDevServer.tap(inspect);
80
+ context.hooks.onAfterStartDevServer.tap(inspect);
81
81
  }
82
82
  return {
83
83
  rspackConfigs
@@ -32,9 +32,9 @@ async function inspectConfig({
32
32
  inspectOptions = {}
33
33
  }) {
34
34
  if (inspectOptions.env) {
35
- process.env.NODE_ENV = inspectOptions.env;
36
- } else if (!process.env.NODE_ENV) {
37
- process.env.NODE_ENV = "development";
35
+ (0, import_shared.setNodeEnv)(inspectOptions.env);
36
+ } else if (!(0, import_shared.getNodeEnv)()) {
37
+ (0, import_shared.setNodeEnv)("development");
38
38
  }
39
39
  const rspackConfigs = bundlerConfigs || (await (0, import_initConfigs.initConfigs)({
40
40
  context,
@@ -92,7 +92,7 @@ async function getConfigUtils(config, chainUtils) {
92
92
  };
93
93
  }
94
94
  async function getChainUtils(target) {
95
- const nodeEnv = process.env.NODE_ENV;
95
+ const nodeEnv = (0, import_shared.getNodeEnv)();
96
96
  return {
97
97
  env: nodeEnv,
98
98
  target,
@@ -3,7 +3,6 @@ export type { Rspack, RspackConfig } from '@rsbuild/shared';
3
3
  export { createContext, createPublicContext } from './core/createContext';
4
4
  export { initPlugins } from '@rsbuild/shared';
5
5
  export { initHooks, type Hooks } from './core/initHooks';
6
- export { withDefaultConfig } from './config';
7
6
  export { initRsbuildConfig } from './core/initConfigs';
8
7
  export { getPluginAPI } from './core/initPlugins';
9
8
  export { applyBaseCSSRule, applyCSSModuleRule } from './plugins/css';
@@ -29,15 +29,13 @@ __export(provider_exports, {
29
29
  initPlugins: () => import_shared.initPlugins,
30
30
  initRsbuildConfig: () => import_initConfigs.initRsbuildConfig,
31
31
  rspackProvider: () => import_provider.rspackProvider,
32
- setHTMLPlugin: () => import_htmlPluginUtil.setHTMLPlugin,
33
- withDefaultConfig: () => import_config.withDefaultConfig
32
+ setHTMLPlugin: () => import_htmlPluginUtil.setHTMLPlugin
34
33
  });
35
34
  module.exports = __toCommonJS(provider_exports);
36
35
  var import_provider = require("./provider");
37
36
  var import_createContext = require("./core/createContext");
38
37
  var import_shared = require("@rsbuild/shared");
39
38
  var import_initHooks = require("./core/initHooks");
40
- var import_config = require("./config");
41
39
  var import_initConfigs = require("./core/initConfigs");
42
40
  var import_initPlugins = require("./core/initPlugins");
43
41
  var import_css = require("./plugins/css");
@@ -56,6 +54,5 @@ var import_shared2 = require("./shared");
56
54
  initPlugins,
57
55
  initRsbuildConfig,
58
56
  rspackProvider,
59
- setHTMLPlugin,
60
- withDefaultConfig
57
+ setHTMLPlugin
61
58
  });
@@ -43,8 +43,8 @@ async function getServerAPIs(options, createDevMiddleware, {
43
43
  compiler: customCompiler,
44
44
  getPortSilently
45
45
  } = {}) {
46
- if (!process.env.NODE_ENV) {
47
- process.env.NODE_ENV = "development";
46
+ if (!(0, import_shared.getNodeEnv)()) {
47
+ (0, import_shared.setNodeEnv)("development");
48
48
  }
49
49
  const rsbuildConfig = options.context.config;
50
50
  const { devServerConfig, port, host, https } = await (0, import_helper.getDevOptions)({
@@ -130,22 +130,17 @@ async function startDevServer(options, createDevMiddleware, {
130
130
  (0, import_shared.debug)("create dev server done");
131
131
  const protocol = https ? "https" : "http";
132
132
  const urls = (0, import_shared.getAddressUrls)({ protocol, port, host });
133
- (0, import_helper.printServerURLs)({
134
- urls,
135
- port,
136
- routes: defaultRoutes,
137
- protocol,
138
- printUrls: devServerConfig.printUrls
139
- });
140
- const compileMiddlewareAPI = await serverAPIs.startCompile();
141
- const devMiddlewares = await serverAPIs.getMiddlewares({
142
- compileMiddlewareAPI
133
+ options.context.hooks.onBeforeCreateCompiler.tap(() => {
134
+ (0, import_helper.printServerURLs)({
135
+ urls,
136
+ port,
137
+ routes: defaultRoutes,
138
+ protocol,
139
+ printUrls: devServerConfig.printUrls
140
+ });
143
141
  });
144
- devMiddlewares.middlewares.forEach((m) => middlewares.use(m));
145
- middlewares.use(import_middlewares.notFoundMiddleware);
146
142
  await serverAPIs.beforeStart();
147
143
  (0, import_shared.debug)("listen dev server");
148
- httpServer.on("upgrade", devMiddlewares.onUpgrade);
149
144
  return new Promise((resolve) => {
150
145
  httpServer.listen(
151
146
  {
@@ -156,6 +151,13 @@ async function startDevServer(options, createDevMiddleware, {
156
151
  if (err) {
157
152
  throw err;
158
153
  }
154
+ const compileMiddlewareAPI = await serverAPIs.startCompile();
155
+ const devMiddlewares = await serverAPIs.getMiddlewares({
156
+ compileMiddlewareAPI
157
+ });
158
+ devMiddlewares.middlewares.forEach((m) => middlewares.use(m));
159
+ middlewares.use(import_middlewares.notFoundMiddleware);
160
+ httpServer.on("upgrade", devMiddlewares.onUpgrade);
159
161
  (0, import_shared.debug)("listen dev server done");
160
162
  await serverAPIs.afterStart();
161
163
  const closeServer = async () => {
@@ -27,24 +27,36 @@ __export(helper_exports, {
27
27
  });
28
28
  module.exports = __toCommonJS(helper_exports);
29
29
  var import_shared = require("@rsbuild/shared");
30
+ const formatPrefix = (prefix) => {
31
+ if (!prefix) {
32
+ return "/";
33
+ }
34
+ const hasLeadingSlash = prefix.startsWith("/");
35
+ const hasTailSlash = prefix.endsWith("/");
36
+ return `${hasLeadingSlash ? "" : "/"}${prefix}${hasTailSlash ? "" : "/"}`;
37
+ };
30
38
  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);
39
+ const formattedPrefix = formatPrefix(prefix);
40
+ return Object.keys(entry).map((entryName) => {
41
+ const isIndex = entryName === "index" && outputStructure !== "nested";
42
+ const displayName = isIndex ? "" : entryName;
43
+ return {
44
+ entryName,
45
+ pathname: formattedPrefix + displayName
46
+ };
47
+ }).sort((a) => a.entryName === "index" ? -1 : 1);
36
48
  };
37
49
  function getURLMessages(urls, routes) {
38
50
  if (routes.length === 1) {
39
51
  return urls.map(
40
52
  ({ label, url }) => ` ${`> ${label.padEnd(10)}`}${import_shared.color.cyan(
41
- (0, import_shared.normalizeUrl)(`${url}/${routes[0].route}`)
53
+ (0, import_shared.normalizeUrl)(`${url}${routes[0].pathname}`)
42
54
  )}
43
55
  `
44
56
  ).join("");
45
57
  }
46
58
  let message = "";
47
- const maxNameLength = Math.max(...routes.map((r) => r.name.length));
59
+ const maxNameLength = Math.max(...routes.map((r) => r.entryName.length));
48
60
  urls.forEach(({ label, url }, index) => {
49
61
  if (index > 0) {
50
62
  message += "\n";
@@ -53,8 +65,8 @@ function getURLMessages(urls, routes) {
53
65
  `;
54
66
  routes.forEach((r) => {
55
67
  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}`))}
68
+ r.entryName.padEnd(maxNameLength + 4)
69
+ )}${import_shared.color.cyan((0, import_shared.normalizeUrl)(`${url}${r.pathname}`))}
58
70
  `;
59
71
  });
60
72
  });
@@ -75,6 +87,7 @@ function printServerURLs({
75
87
  const newUrls = printUrls({
76
88
  urls: urls.map((item) => item.url),
77
89
  port,
90
+ routes,
78
91
  protocol
79
92
  });
80
93
  if (!newUrls) {
@@ -123,8 +123,8 @@ class RsbuildProdServer {
123
123
  }
124
124
  }
125
125
  async function startProdServer(context, rsbuildConfig, { getPortSilently } = {}) {
126
- if (!process.env.NODE_ENV) {
127
- process.env.NODE_ENV = "production";
126
+ if (!(0, import_shared.getNodeEnv)()) {
127
+ (0, import_shared.setNodeEnv)("production");
128
128
  }
129
129
  const { serverConfig, port, host, https } = await (0, import_helper.getServerOptions)({
130
130
  rsbuildConfig,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "bugs": {
@@ -57,7 +57,7 @@
57
57
  "core-js": "~3.32.2",
58
58
  "html-webpack-plugin": "npm:html-rspack-plugin@5.5.7",
59
59
  "postcss": "^8.4.33",
60
- "@rsbuild/shared": "0.3.3"
60
+ "@rsbuild/shared": "0.3.5"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@types/node": "16.x",