@rsbuild/core 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export = any;
@@ -0,0 +1 @@
1
+ (()=>{var e={426:(e,t,n)=>{const r=n(310);const s=n(17);const i=n(80);e.exports=(e,t,n)=>{if(typeof e==="function"){n=e;e=undefined}if(typeof t==="function"){n=t;t=undefined}t=t||process.cwd();return function launchEditorMiddleware(o,a,c){const{file:p}=r.parse(o.url,true).query||{};if(!p){a.statusCode=500;a.end(`launch-editor-middleware: required query param "file" is missing.`)}else{i(s.resolve(t,p),e,n);a.end()}}}},881:e=>{e.exports={atom:"atom",Brackets:"brackets","code-insiders":"code-insiders",code:"code",vscodium:"vscodium",codium:"codium",emacs:"emacs",gvim:"gvim","idea.sh":"idea","phpstorm.sh":"phpstorm","pycharm.sh":"pycharm","rubymine.sh":"rubymine",sublime_text:"subl",vim:"vim","webstorm.sh":"webstorm","goland.sh":"goland","rider.sh":"rider"}},341:e=>{e.exports={"/Applications/Atom.app/Contents/MacOS/Atom":"atom","/Applications/Atom Beta.app/Contents/MacOS/Atom Beta":"/Applications/Atom Beta.app/Contents/MacOS/Atom Beta","/Applications/Brackets.app/Contents/MacOS/Brackets":"brackets","/Applications/Sublime Text.app/Contents/MacOS/Sublime Text":"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl","/Applications/Sublime Text.app/Contents/MacOS/sublime_text":"/Applications/Sublime Text.app/Contents/SharedSupport/bin/subl","/Applications/Sublime Text 2.app/Contents/MacOS/Sublime Text 2":"/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl","/Applications/Sublime Text Dev.app/Contents/MacOS/Sublime Text":"/Applications/Sublime Text Dev.app/Contents/SharedSupport/bin/subl","/Applications/Visual Studio Code.app/Contents/MacOS/Electron":"code","/Applications/Visual Studio Code - Insiders.app/Contents/MacOS/Electron":"code-insiders","/Applications/VSCodium.app/Contents/MacOS/Electron":"codium","/Applications/AppCode.app/Contents/MacOS/appcode":"/Applications/AppCode.app/Contents/MacOS/appcode","/Applications/CLion.app/Contents/MacOS/clion":"/Applications/CLion.app/Contents/MacOS/clion","/Applications/IntelliJ IDEA.app/Contents/MacOS/idea":"/Applications/IntelliJ IDEA.app/Contents/MacOS/idea","/Applications/PhpStorm.app/Contents/MacOS/phpstorm":"/Applications/PhpStorm.app/Contents/MacOS/phpstorm","/Applications/PyCharm.app/Contents/MacOS/pycharm":"/Applications/PyCharm.app/Contents/MacOS/pycharm","/Applications/PyCharm CE.app/Contents/MacOS/pycharm":"/Applications/PyCharm CE.app/Contents/MacOS/pycharm","/Applications/RubyMine.app/Contents/MacOS/rubymine":"/Applications/RubyMine.app/Contents/MacOS/rubymine","/Applications/WebStorm.app/Contents/MacOS/webstorm":"/Applications/WebStorm.app/Contents/MacOS/webstorm","/Applications/MacVim.app/Contents/MacOS/MacVim":"mvim","/Applications/GoLand.app/Contents/MacOS/goland":"/Applications/GoLand.app/Contents/MacOS/goland","/Applications/Rider.app/Contents/MacOS/rider":"/Applications/Rider.app/Contents/MacOS/rider"}},3:e=>{e.exports=["Brackets.exe","Code.exe","Code - Insiders.exe","VSCodium.exe","atom.exe","sublime_text.exe","notepad++.exe","clion.exe","clion64.exe","idea.exe","idea64.exe","phpstorm.exe","phpstorm64.exe","pycharm.exe","pycharm64.exe","rubymine.exe","rubymine64.exe","webstorm.exe","webstorm64.exe","goland.exe","goland64.exe","rider.exe","rider64.exe"]},417:(e,t,n)=>{const r=n(17);e.exports=function getArgumentsForPosition(e,t,n,s=1){const i=r.basename(e).replace(/\.(exe|cmd|bat)$/i,"");switch(i){case"atom":case"Atom":case"Atom Beta":case"subl":case"sublime":case"sublime_text":case"wstorm":case"charm":return[`${t}:${n}:${s}`];case"notepad++":return["-n"+n,"-c"+s,t];case"vim":case"mvim":return[`+call cursor(${n}, ${s})`,t];case"joe":case"gvim":return["+"+`${n}`,t];case"emacs":case"emacsclient":return[`+${n}:${s}`,t];case"rmate":case"mate":case"mine":return["--line",n,t];case"code":case"Code":case"code-insiders":case"Code - Insiders":case"codium":case"vscodium":case"VSCodium":return["-r","-g",`${t}:${n}:${s}`];case"appcode":case"clion":case"clion64":case"idea":case"idea64":case"phpstorm":case"phpstorm64":case"pycharm":case"pycharm64":case"rubymine":case"rubymine64":case"webstorm":case"webstorm64":case"goland":case"goland64":case"rider":case"rider64":return["--line",n,"--column",s,t]}if(process.env.LAUNCH_EDITOR){return[t,n,s]}return[t]}},841:(e,t,n)=>{const r=n(17);const s=n(522);const i=n(81);const o=n(341);const a=n(881);const c=n(3);e.exports=function guessEditor(e){if(e){return s.parse(e)}if(process.env.LAUNCH_EDITOR){return[process.env.LAUNCH_EDITOR]}if(process.versions.webcontainer){return[process.env.EDITOR||"code"]}try{if(process.platform==="darwin"){const e=i.execSync("ps x -o comm=",{stdio:["pipe","pipe","ignore"]}).toString();const t=Object.keys(o);const n=e.split("\n");for(let r=0;r<t.length;r++){const s=t[r];if(e.indexOf(s)!==-1){return[o[s]]}const i=s.replace("/Applications","");if(e.indexOf(i)!==-1){if(s!==o[s]){return[o[s]]}const e=n.find((e=>e.endsWith(i)));if(e!==undefined){return[e]}}}}else if(process.platform==="win32"){const e=i.execSync('powershell -NoProfile -Command "Get-CimInstance -Query \\"select executablepath from win32_process where executablepath is not null\\" | % { $_.ExecutablePath }"',{stdio:["pipe","pipe","ignore"]}).toString();const t=e.split("\r\n");for(let e=0;e<t.length;e++){const n=t[e].trim();const s=r.basename(n);if(c.indexOf(s)!==-1){return[n]}}}else if(process.platform==="linux"){const e=i.execSync("ps x --no-heading -o comm --sort=comm",{stdio:["pipe","pipe","ignore"]}).toString();const t=Object.keys(a);for(let n=0;n<t.length;n++){const r=t[n];if(e.indexOf(r)!==-1){return[a[r]]}}}}catch(e){}if(process.env.VISUAL){return[process.env.VISUAL]}else if(process.env.EDITOR){return[process.env.EDITOR]}return[null]}},80:(e,t,n)=>{const r=n(147);const s=n(37);const i=n(17);const o=n(802);const a=n(81);const c=n(841);const p=n(417);function wrapErrorCallback(e){return(t,n)=>{console.log();console.log(o.red("Could not open "+i.basename(t)+" in the editor."));if(n){if(n[n.length-1]!=="."){n+="."}console.log(o.red("The editor process exited with an error: "+n))}console.log();if(e)e(t,n)}}function isTerminalEditor(e){switch(e){case"vim":case"emacs":case"nano":return true}return false}const l=/:(\d+)(:(\d+))?$/;function parseFile(e){const t=e.replace(l,"");const n=e.match(l);const r=n&&n[1];const s=n&&n[3];return{fileName:t,lineNumber:r,columnNumber:s}}let u=null;function launchEditor(e,t,n){const o=parseFile(e);let{fileName:l}=o;const{lineNumber:d,columnNumber:m}=o;if(!r.existsSync(l)){return}if(typeof t==="function"){n=t;t=undefined}n=wrapErrorCallback(n);const[f,...x]=c(t);if(!f){n(l,null);return}if(process.platform==="linux"&&l.startsWith("/mnt/")&&/Microsoft/i.test(s.release())){l=i.relative("",l)}if(d){const e=p(f,l,d,m);x.push.apply(x,e)}else{x.push(l)}if(u&&isTerminalEditor(f)){u.kill("SIGKILL")}if(process.platform==="win32"){u=a.spawn("cmd.exe",["/C",f].concat(x),{stdio:"inherit"})}else{u=a.spawn(f,x,{stdio:"inherit"})}u.on("exit",(function(e){u=null;if(e){n(l,"(code "+e+")")}}));u.on("error",(function(e){n(l,e.message)}))}e.exports=launchEditor},522:(e,t,n)=>{"use strict";t.quote=n(392);t.parse=n(145)},145:e=>{"use strict";var t="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")";var n=new RegExp("^"+t+"$");var r="|&;()<> \\t";var s='"((\\\\"|[^"])*?)"';var i="'((\\\\'|[^'])*?)'";var o=/^#$/;var a="'";var c='"';var p="$";var l="";var u=4294967296;for(var d=0;d<4;d++){l+=(u*Math.random()).toString(16)}var m=new RegExp("^"+l);function matchAll(e,t){var n=t.lastIndex;var r=[];var s;while(s=t.exec(e)){r.push(s);if(t.lastIndex===s.index){t.lastIndex+=1}}t.lastIndex=n;return r}function getVar(e,t,n){var r=typeof e==="function"?e(n):e[n];if(typeof r==="undefined"&&n!=""){r=""}else if(typeof r==="undefined"){r="$"}if(typeof r==="object"){return t+l+JSON.stringify(r)+l}return t+r}function parseInternal(e,l,u){if(!u){u={}}var d=u.escape||"\\";var m="(\\"+d+"['\""+r+"]|[^\\s'\""+r+"])+";var f=new RegExp(["("+t+")","("+m+"|"+s+"|"+i+")+"].join("|"),"g");var x=matchAll(e,f);if(x.length===0){return[]}if(!l){l={}}var h=false;return x.map((function(t){var r=t[0];if(!r||h){return void undefined}if(n.test(r)){return{op:r}}var s=false;var i=false;var u="";var m=false;var f;function parseEnvVar(){f+=1;var e;var t;var n=r.charAt(f);if(n==="{"){f+=1;if(r.charAt(f)==="}"){throw new Error("Bad substitution: "+r.slice(f-2,f+1))}e=r.indexOf("}",f);if(e<0){throw new Error("Bad substitution: "+r.slice(f))}t=r.slice(f,e);f=e}else if(/[*@#?$!_-]/.test(n)){t=n;f+=1}else{var s=r.slice(f);e=s.match(/[^\w\d_]/);if(!e){t=s;f=r.length}else{t=s.slice(0,e.index);f+=e.index-1}}return getVar(l,"",t)}for(f=0;f<r.length;f++){var x=r.charAt(f);m=m||!s&&(x==="*"||x==="?");if(i){u+=x;i=false}else if(s){if(x===s){s=false}else if(s==a){u+=x}else{if(x===d){f+=1;x=r.charAt(f);if(x===c||x===d||x===p){u+=x}else{u+=d+x}}else if(x===p){u+=parseEnvVar()}else{u+=x}}}else if(x===c||x===a){s=x}else if(n.test(x)){return{op:r}}else if(o.test(x)){h=true;var b={comment:e.slice(t.index+f+1)};if(u.length){return[u,b]}return[b]}else if(x===d){i=true}else if(x===p){u+=parseEnvVar()}else{u+=x}}if(m){return{op:"glob",pattern:u}}return u})).reduce((function(e,t){return typeof t==="undefined"?e:e.concat(t)}),[])}e.exports=function parse(e,t,n){var r=parseInternal(e,t,n);if(typeof t!=="function"){return r}return r.reduce((function(e,t){if(typeof t==="object"){return e.concat(t)}var n=t.split(RegExp("("+l+".*?"+l+")","g"));if(n.length===1){return e.concat(n[0])}return e.concat(n.filter(Boolean).map((function(e){if(m.test(e)){return JSON.parse(e.split(l)[1])}return e})))}),[])}},392:e=>{"use strict";e.exports=function quote(e){return e.map((function(e){if(e&&typeof e==="object"){return e.op.replace(/(.)/g,"\\$1")}if(/["\s]/.test(e)&&!/'/.test(e)){return"'"+e.replace(/(['\\])/g,"\\$1")+"'"}if(/["'\s]/.test(e)){return'"'+e.replace(/(["\\$`!])/g,"\\$1")+'"'}return String(e).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")})).join(" ")}},802:e=>{"use strict";e.exports=require("@rsbuild/shared/picocolors")},81:e=>{"use strict";e.exports=require("child_process")},147:e=>{"use strict";e.exports=require("fs")},37:e=>{"use strict";e.exports=require("os")},17:e=>{"use strict";e.exports=require("path")},310:e=>{"use strict";e.exports=require("url")}};var t={};function __nccwpck_require__(n){var r=t[n];if(r!==undefined){return r.exports}var s=t[n]={exports:{}};var i=true;try{e[n](s,s.exports,__nccwpck_require__);i=false}finally{if(i)delete t[n]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var n=__nccwpck_require__(426);module.exports=n})();
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017-present, Yuxi (Evan) You
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ {"name":"launch-editor-middleware","author":"Evan You","version":"2.6.1","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.4");
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.6");
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,12 +99,9 @@ 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
106
  env: (0, import_shared.getNodeEnv)(),
113
107
  command
@@ -118,14 +112,50 @@ async function loadConfig({
118
112
  }
119
113
  return result;
120
114
  }
115
+ if (!(0, import_shared.isObject)(configExport)) {
116
+ throw new Error(
117
+ `Rsbuild config must be an object or a function that returns an object, get ${import_shared.color.yellow(
118
+ configExport
119
+ )}`
120
+ );
121
+ }
121
122
  return configExport;
122
123
  } catch (err) {
123
124
  import_shared.logger.error(`Failed to load file: ${import_shared.color.dim(configFile)}`);
124
125
  throw err;
125
126
  }
126
127
  }
128
+ async function loadConfig({
129
+ cwd,
130
+ path
131
+ }) {
132
+ const configFile = resolveConfigPath(cwd, path);
133
+ if (!configFile) {
134
+ return {};
135
+ }
136
+ return loadConfigByPath(configFile);
137
+ }
138
+ async function loadConfigV2({
139
+ cwd,
140
+ path
141
+ }) {
142
+ const configFile = resolveConfigPath(cwd, path);
143
+ if (!configFile) {
144
+ return {
145
+ content: {},
146
+ filePath: configFile
147
+ };
148
+ }
149
+ return {
150
+ content: await loadConfigByPath(configFile),
151
+ filePath: configFile
152
+ };
153
+ }
127
154
  // Annotate the CommonJS export names for ESM import in node:
128
155
  0 && (module.exports = {
129
156
  defineConfig,
130
- loadConfig
157
+ loadConfig,
158
+ loadConfigByPath,
159
+ loadConfigV2,
160
+ watchFiles
131
161
  });
@@ -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.4"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.3.6"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
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.4";
41
+ const version = "0.3.6";
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 nodeEnv = (0, import_shared.getNodeEnv)();
42
- return [".env", ".env.local", `.env.${nodeEnv}`, `.env.${nodeEnv}.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
  });
@@ -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
  }
@@ -86,13 +86,13 @@ function splitByExperience(ctx) {
86
86
  }
87
87
  };
88
88
  }
89
- const MODULE_PATH_REGEX = /[\\/]node_modules[\\/](\.pnpm[\\/])?(?:(@[^[\\/]+)(?:[\\/]))?([^\\/]+)/;
89
+ const MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\/])?([^\\/]+)/;
90
90
  function getPackageNameFromModulePath(modulePath) {
91
91
  const handleModuleContext = modulePath?.match(MODULE_PATH_REGEX);
92
92
  if (!handleModuleContext) {
93
93
  return void 0;
94
94
  }
95
- const [, , scope, name] = handleModuleContext;
95
+ const [, scope, name] = handleModuleContext;
96
96
  const packageName = ["npm", (scope ?? "").replace("@", ""), name].filter(Boolean).join(".");
97
97
  return packageName;
98
98
  }
@@ -43,7 +43,7 @@ async function createContextByConfig(options, bundlerType, config = {}) {
43
43
  const context = {
44
44
  entry: config.source?.entry || {},
45
45
  targets: config.output?.targets || [],
46
- version: "0.3.4",
46
+ version: "0.3.6",
47
47
  rootPath,
48
48
  distPath,
49
49
  cachePath,
@@ -155,7 +155,13 @@ async function startDevServer(options, createDevMiddleware, {
155
155
  const devMiddlewares = await serverAPIs.getMiddlewares({
156
156
  compileMiddlewareAPI
157
157
  });
158
- devMiddlewares.middlewares.forEach((m) => middlewares.use(m));
158
+ devMiddlewares.middlewares.forEach((item) => {
159
+ if (Array.isArray(item)) {
160
+ middlewares.use(...item);
161
+ } else {
162
+ middlewares.use(item);
163
+ }
164
+ });
159
165
  middlewares.use(import_middlewares.notFoundMiddleware);
160
166
  httpServer.on("upgrade", devMiddlewares.onUpgrade);
161
167
  (0, import_shared.debug)("listen dev server done");
@@ -1,4 +1,4 @@
1
- import type { UpgradeEvent, RequestHandler, DevMiddlewaresConfig, CompileMiddlewareAPI } from '@rsbuild/shared';
1
+ import type { Middlewares, UpgradeEvent, DevMiddlewaresConfig, CompileMiddlewareAPI } from '@rsbuild/shared';
2
2
  export type RsbuildDevMiddlewareOptions = {
3
3
  pwd: string;
4
4
  dev: DevMiddlewaresConfig;
@@ -10,5 +10,5 @@ export type RsbuildDevMiddlewareOptions = {
10
10
  export declare const getMiddlewares: (options: RsbuildDevMiddlewareOptions) => Promise<{
11
11
  close: () => Promise<void>;
12
12
  onUpgrade: UpgradeEvent;
13
- middlewares: RequestHandler[];
13
+ middlewares: Middlewares;
14
14
  }>;
@@ -93,6 +93,8 @@ const applyDefaultMiddlewares = async ({
93
93
  middlewares.push(middleware);
94
94
  });
95
95
  }
96
+ const { default: launchEditorMiddleware } = await Promise.resolve().then(() => __toESM(require("../../compiled/launch-editor-middleware")));
97
+ middlewares.push(["/__open-in-editor", launchEditorMiddleware()]);
96
98
  if (compileMiddlewareAPI) {
97
99
  middlewares.push(compileMiddlewareAPI.middleware);
98
100
  upgradeEvents.push(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.3.4",
3
+ "version": "0.3.6",
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.4"
60
+ "@rsbuild/shared": "0.3.6"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@types/node": "16.x",