Skip to content

Commit 51e9195

Browse files
authored
feat: better config __dirname support (#8442)
1 parent f59adf8 commit 51e9195

File tree

2 files changed

+18
-16
lines changed

2 files changed

+18
-16
lines changed

docs/config/index.md

+5-5
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,14 @@ vite --config my-config.js
2424
```
2525

2626
::: tip NOTE
27-
Vite will replace `__filename`, `__dirname`, and `import.meta.url` in config files and its deps. Using these as variable names or passing as a parameter to a function with string double quote (example `console.log`) will result in an error:
27+
Vite will inject `__filename`, `__dirname` in config files and its deps. Declaring these variables at top level will result in an error:
2828

2929
```js
30-
const __filename = "value"
31-
// will be transformed to
32-
const "path/vite.config.js" = "value"
30+
const __filename = 'value' // SyntaxError: Identifier '__filename' has already been declared
3331

34-
console.log("import.meta.url") // break error on build
32+
const func = () => {
33+
const __filename = 'value' // no error
34+
}
3535
```
3636

3737
:::

packages/vite/src/node/config.ts

+13-11
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,7 @@ async function bundleConfigFile(
772772
fileName: string,
773773
isESM = false
774774
): Promise<{ code: string; dependencies: string[] }> {
775+
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
775776
const result = await build({
776777
absWorkingDir: process.cwd(),
777778
entryPoints: [fileName],
@@ -782,6 +783,9 @@ async function bundleConfigFile(
782783
format: isESM ? 'esm' : 'cjs',
783784
sourcemap: 'inline',
784785
metafile: true,
786+
define: {
787+
'import.meta.url': importMetaUrlVarName
788+
},
785789
plugins: [
786790
{
787791
name: 'externalize-deps',
@@ -797,22 +801,20 @@ async function bundleConfigFile(
797801
}
798802
},
799803
{
800-
name: 'replace-import-meta',
804+
name: 'inject-file-scope-variables',
801805
setup(build) {
802806
build.onLoad({ filter: /\.[jt]s$/ }, async (args) => {
803807
const contents = await fs.promises.readFile(args.path, 'utf8')
808+
const injectValues =
809+
`const __dirname = ${JSON.stringify(path.dirname(args.path))};` +
810+
`const __filename = ${JSON.stringify(args.path)};` +
811+
`const ${importMetaUrlVarName} = ${JSON.stringify(
812+
pathToFileURL(args.path).href
813+
)};`
814+
804815
return {
805816
loader: args.path.endsWith('.ts') ? 'ts' : 'js',
806-
contents: contents
807-
.replace(
808-
/\bimport\.meta\.url\b/g,
809-
JSON.stringify(pathToFileURL(args.path).href)
810-
)
811-
.replace(
812-
/\b__dirname\b/g,
813-
JSON.stringify(path.dirname(args.path))
814-
)
815-
.replace(/\b__filename\b/g, JSON.stringify(args.path))
817+
contents: injectValues + contents
816818
}
817819
})
818820
}

0 commit comments

Comments
 (0)