From 1e078ad1902ae980741d6920fc3a72d182fcf179 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Sat, 16 Jul 2022 17:26:23 +0900 Subject: [PATCH] feat: allow declaring dirname (#9154) --- docs/config/index.md | 13 ------------- packages/vite/src/node/config.ts | 10 ++++++++-- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/docs/config/index.md b/docs/config/index.md index 34675192fe6484..0ffd9f05967fbd 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -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: diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index 6b9195f17927ed..ef1fdbe522c133 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -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(), @@ -894,6 +896,8 @@ async function bundleConfigFile( sourcemap: 'inline', metafile: true, define: { + __dirname: dirnameVarName, + __filename: filenameVarName, 'import.meta.url': importMetaUrlVarName }, plugins: [ @@ -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 )};`