Skip to content

Commit 1e078ad

Browse files
authored
feat: allow declaring dirname (#9154)
1 parent 5844d8e commit 1e078ad

File tree

2 files changed

+8
-15
lines changed

2 files changed

+8
-15
lines changed

docs/config/index.md

-13
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,6 @@ You can also explicitly specify a config file to use with the `--config` CLI opt
2323
vite --config my-config.js
2424
```
2525

26-
::: tip NOTE
27-
Vite will inject `__filename`, `__dirname` in config files and its deps. Declaring these variables at top level will result in an error:
28-
29-
```js
30-
const __filename = 'value' // SyntaxError: Identifier '__filename' has already been declared
31-
32-
const func = () => {
33-
const __filename = 'value' // no error
34-
}
35-
```
36-
37-
:::
38-
3926
## Config Intellisense
4027

4128
Since Vite ships with TypeScript typings, you can leverage your IDE's intellisense with jsdoc type hints:

packages/vite/src/node/config.ts

+8-2
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,8 @@ async function bundleConfigFile(
882882
fileName: string,
883883
isESM: boolean
884884
): Promise<{ code: string; dependencies: string[] }> {
885+
const dirnameVarName = '__vite_injected_original_dirname'
886+
const filenameVarName = '__vite_injected_original_filename'
885887
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
886888
const result = await build({
887889
absWorkingDir: process.cwd(),
@@ -894,6 +896,8 @@ async function bundleConfigFile(
894896
sourcemap: 'inline',
895897
metafile: true,
896898
define: {
899+
__dirname: dirnameVarName,
900+
__filename: filenameVarName,
897901
'import.meta.url': importMetaUrlVarName
898902
},
899903
plugins: [
@@ -943,8 +947,10 @@ async function bundleConfigFile(
943947
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
944948
const contents = await fs.promises.readFile(args.path, 'utf8')
945949
const injectValues =
946-
`const __dirname = ${JSON.stringify(path.dirname(args.path))};` +
947-
`const __filename = ${JSON.stringify(args.path)};` +
950+
`const ${dirnameVarName} = ${JSON.stringify(
951+
path.dirname(args.path)
952+
)};` +
953+
`const ${filenameVarName} = ${JSON.stringify(args.path)};` +
948954
`const ${importMetaUrlVarName} = ${JSON.stringify(
949955
pathToFileURL(args.path).href
950956
)};`

0 commit comments

Comments
 (0)