Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow declaring __dirname in config #9154

Merged
merged 1 commit into from Jul 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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