Skip to content

Commit

Permalink
feat: allow declaring dirname (#9154)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Jul 16, 2022
1 parent 5844d8e commit 1e078ad
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 15 deletions.
13 changes: 0 additions & 13 deletions docs/config/index.md
Expand Up @@ -23,19 +23,6 @@ You can also explicitly specify a config file to use with the `--config` CLI opt
vite --config my-config.js
```

::: tip NOTE
Vite will inject `__filename`, `__dirname` in config files and its deps. Declaring these variables at top level will result in an error:

```js
const __filename = 'value' // SyntaxError: Identifier '__filename' has already been declared

const func = () => {
const __filename = 'value' // no error
}
```

:::

## Config Intellisense

Since Vite ships with TypeScript typings, you can leverage your IDE's intellisense with jsdoc type hints:
Expand Down
10 changes: 8 additions & 2 deletions packages/vite/src/node/config.ts
Expand Up @@ -882,6 +882,8 @@ async function bundleConfigFile(
fileName: string,
isESM: boolean
): Promise<{ code: string; dependencies: string[] }> {
const dirnameVarName = '__vite_injected_original_dirname'
const filenameVarName = '__vite_injected_original_filename'
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
const result = await build({
absWorkingDir: process.cwd(),
Expand All @@ -894,6 +896,8 @@ async function bundleConfigFile(
sourcemap: 'inline',
metafile: true,
define: {
__dirname: dirnameVarName,
__filename: filenameVarName,
'import.meta.url': importMetaUrlVarName
},
plugins: [
Expand Down Expand Up @@ -943,8 +947,10 @@ async function bundleConfigFile(
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
const contents = await fs.promises.readFile(args.path, 'utf8')
const injectValues =
`const __dirname = ${JSON.stringify(path.dirname(args.path))};` +
`const __filename = ${JSON.stringify(args.path)};` +
`const ${dirnameVarName} = ${JSON.stringify(
path.dirname(args.path)
)};` +
`const ${filenameVarName} = ${JSON.stringify(args.path)};` +
`const ${importMetaUrlVarName} = ${JSON.stringify(
pathToFileURL(args.path).href
)};`
Expand Down

0 comments on commit 1e078ad

Please sign in to comment.