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: better config __dirname support #8442

Merged
merged 1 commit into from Jun 8, 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
10 changes: 5 additions & 5 deletions docs/config/index.md
Expand Up @@ -24,14 +24,14 @@ vite --config my-config.js
```

::: tip NOTE
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:
Vite will inject `__filename`, `__dirname` in config files and its deps. Declaring these variables at top level will result in an error:
Copy link
Member Author

@sapphi-red sapphi-red Jun 2, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In CJS, the following code fails, so it is not a special thing.

const __dirname = ''

But here it also happens with ESM. This is the reason I left this note.

Also I didn't mention import.meta.url because __vite_injected_original_import_meta_url will rarely conflict.


```js
const __filename = "value"
// will be transformed to
const "path/vite.config.js" = "value"
const __filename = 'value' // SyntaxError: Identifier '__filename' has already been declared

console.log("import.meta.url") // break error on build
const func = () => {
const __filename = 'value' // no error
}
```

:::
Expand Down
24 changes: 13 additions & 11 deletions packages/vite/src/node/config.ts
Expand Up @@ -790,6 +790,7 @@ async function bundleConfigFile(
fileName: string,
isESM = false
): Promise<{ code: string; dependencies: string[] }> {
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
const result = await build({
absWorkingDir: process.cwd(),
entryPoints: [fileName],
Expand All @@ -800,6 +801,9 @@ async function bundleConfigFile(
format: isESM ? 'esm' : 'cjs',
sourcemap: 'inline',
metafile: true,
define: {
'import.meta.url': importMetaUrlVarName
},
plugins: [
{
name: 'externalize-deps',
Expand All @@ -815,22 +819,20 @@ async function bundleConfigFile(
}
},
{
name: 'replace-import-meta',
name: 'inject-file-scope-variables',
setup(build) {
build.onLoad({ filter: /\.[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)};` +
bluwy marked this conversation as resolved.
Show resolved Hide resolved
`const ${importMetaUrlVarName} = ${JSON.stringify(
pathToFileURL(args.path).href
)};`

return {
loader: args.path.endsWith('.ts') ? 'ts' : 'js',
contents: contents
.replace(
/\bimport\.meta\.url\b/g,
JSON.stringify(pathToFileURL(args.path).href)
)
.replace(
/\b__dirname\b/g,
JSON.stringify(path.dirname(args.path))
)
.replace(/\b__filename\b/g, JSON.stringify(args.path))
contents: injectValues + contents
}
})
}
Expand Down