From 6dcb1827ef5b1e916e74b8326624cddac91cb040 Mon Sep 17 00:00:00 2001 From: sapphi-red <49056869+sapphi-red@users.noreply.github.com> Date: Wed, 28 Jan 2026 13:48:52 +0900 Subject: [PATCH 1/3] refactor: use `import.meta.dirname` everywhere --- docs/.vitepress/config.ts | 2 +- docs/guide/api-environment-frameworks.md | 5 +- docs/guide/api-javascript.md | 10 +--- docs/guide/build.md | 21 ++----- docs/guide/ssr.md | 6 +- packages/create-vite/__tests__/cli.spec.ts | 34 ++++++----- .../src/__tests__/readme.spec.ts | 2 +- packages/vite/rolldown.config.ts | 24 ++++---- .../vite/src/node/__tests__/build.spec.ts | 55 +++++++++-------- .../vite/src/node/__tests__/config.spec.ts | 2 +- packages/vite/src/node/__tests__/dev.spec.ts | 2 +- packages/vite/src/node/__tests__/env.spec.ts | 20 +++---- packages/vite/src/node/__tests__/http.spec.ts | 12 ++-- .../src/node/__tests__/plugins/css.spec.ts | 11 ++-- .../plugins/dynamicImportVar/parse.spec.ts | 11 ++-- .../plugins/importGlob/fixture.spec.ts | 13 ++-- .../src/node/__tests__/plugins/terser.spec.ts | 5 +- .../node/server/__tests__/search-root.spec.ts | 25 ++++---- .../server-worker-runner.invoke.spec.ts | 2 +- .../__tests__/server-worker-runner.spec.ts | 2 +- .../src/node/ssr/runtime/__tests__/utils.ts | 2 +- playground/alias/vite.config.js | 12 ++-- playground/assets/vite.config.js | 4 +- playground/backend-integration/vite.config.js | 6 +- playground/csp/vite.config.js | 8 +-- playground/css-codesplit-cjs/vite.config.js | 4 +- playground/css-codesplit/vite.config.js | 12 ++-- playground/css-lightningcss-proxy/server.js | 3 +- playground/css-lightningcss/vite.config.js | 2 +- playground/css-no-codesplit/vite.config.js | 4 +- playground/css-sourcemap/vite.config.js | 2 +- .../css-postcss-plugins-different-dir.spec.ts | 2 +- playground/css/postcss-caching/css.spec.ts | 4 +- playground/css/vite.config.js | 25 ++++---- .../dynamic-import-inline/vite.config.js | 2 +- playground/dynamic-import/vite.config.js | 20 ++++--- playground/external/vite.config.js | 2 +- .../fs-serve/__tests__/fs-serve.spec.ts | 4 +- playground/fs-serve/root/vite.config-base.js | 6 +- playground/fs-serve/root/vite.config-deny.js | 6 +- playground/fs-serve/root/vite.config.js | 6 +- .../glob-import/__tests__/glob-import.spec.ts | 2 +- playground/glob-import/vite.config.ts | 10 ++-- playground/hmr-root/vite.config.ts | 5 +- playground/hmr/vite.config.ts | 2 +- playground/html/vite.config.js | 60 ++++++++++--------- .../vite.config-no-polyfills-no-systemjs.js | 5 +- playground/legacy/vite.config-no-polyfills.js | 2 +- playground/legacy/vite.config-watch.js | 5 +- playground/legacy/vite.config.js | 6 +- playground/lib/__tests__/serve.ts | 25 ++++---- playground/lib/vite.config.js | 4 +- playground/lib/vite.dyimport.config.js | 2 +- .../lib/vite.helpers-injection.config.js | 2 +- playground/lib/vite.multiple-output.config.js | 8 +-- playground/lib/vite.named-exports.config.js | 2 +- playground/lib/vite.terser.config.js | 2 +- .../multiple-entrypoints/vite.config.js | 54 +++++++++-------- playground/nested-deps/vite.config.js | 2 +- playground/optimize-missing-deps/server.js | 4 +- playground/resolve/vite.config.js | 10 +++- playground/ssr-conditions/server.js | 7 +-- playground/ssr-deps/server.js | 7 +-- .../ssr-html/__tests__/ssr-html.spec.ts | 4 +- playground/ssr-html/server.js | 4 +- playground/ssr-html/test-stacktrace.js | 8 +-- playground/ssr-noexternal/server.js | 5 +- playground/ssr-pug/server.js | 5 +- playground/ssr-webworker/worker.js | 8 +-- playground/ssr/server.js | 6 +- playground/tailwind-v3/tailwind.config.ts | 4 +- playground/tailwind-v3/vite.config.ts | 2 +- playground/tailwind/tailwind.config.ts | 6 +- playground/tailwind/vite.config.ts | 2 +- playground/transform-plugin/vite.config.js | 2 +- .../__tests__/tsconfig-json.spec.ts | 8 +-- playground/vitestGlobalSetup.ts | 6 +- playground/vitestSetup.ts | 2 +- playground/worker/vite.config-es.js | 2 +- playground/worker/vite.config-iife.js | 2 +- .../worker/vite.config-relative-base-iife.js | 2 +- .../worker/vite.config-relative-base.js | 2 +- playground/worker/worker-sourcemap-config.js | 2 +- vitest.config.e2e.ts | 3 +- 84 files changed, 337 insertions(+), 374 deletions(-) diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 60c876682e8ff6..0680f80f954da8 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -79,7 +79,7 @@ function inlineScript(file: string): HeadConfig { 'script', {}, fs.readFileSync( - path.resolve(__dirname, `./inlined-scripts/${file}`), + path.resolve(import.meta.dirname, `./inlined-scripts/${file}`), 'utf-8', ), ] diff --git a/docs/guide/api-environment-frameworks.md b/docs/guide/api-environment-frameworks.md index fd8171b267c7e6..089ce3f3dca1a6 100644 --- a/docs/guide/api-environment-frameworks.md +++ b/docs/guide/api-environment-frameworks.md @@ -52,11 +52,8 @@ Given a Vite server configured in middleware mode as described by the [SSR setup ```js import fs from 'node:fs' import path from 'node:path' -import { fileURLToPath } from 'node:url' import { createServer } from 'vite' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - const viteServer = await createServer({ server: { middlewareMode: true }, appType: 'custom', @@ -75,7 +72,7 @@ app.use('*', async (req, res, next) => { const url = req.originalUrl // 1. Read index.html - const indexHtmlPath = path.resolve(__dirname, 'index.html') + const indexHtmlPath = path.resolve(import.meta.dirname, 'index.html') let template = fs.readFileSync(indexHtmlPath, 'utf-8') // 2. Apply Vite HTML transforms. This injects the Vite HMR client, diff --git a/docs/guide/api-javascript.md b/docs/guide/api-javascript.md index a3a87f9e3dd26f..d12433f618aa40 100644 --- a/docs/guide/api-javascript.md +++ b/docs/guide/api-javascript.md @@ -13,15 +13,12 @@ async function createServer(inlineConfig?: InlineConfig): Promise **Example Usage:** ```ts twoslash -import { fileURLToPath } from 'node:url' import { createServer } from 'vite' -const __dirname = fileURLToPath(new URL('.', import.meta.url)) - const server = await createServer({ // any valid user config options, plus `mode` and `configFile` configFile: false, - root: __dirname, + root: import.meta.dirname, server: { port: 1337, }, @@ -210,13 +207,10 @@ async function build( ```ts twoslash [vite.config.js] import path from 'node:path' -import { fileURLToPath } from 'node:url' import { build } from 'vite' -const __dirname = fileURLToPath(new URL('.', import.meta.url)) - await build({ - root: path.resolve(__dirname, './project'), + root: path.resolve(import.meta.dirname, './project'), base: '/foo/', build: { rollupOptions: { diff --git a/docs/guide/build.md b/docs/guide/build.md index 58bb662ab9d2a7..3a28937e3e04b7 100644 --- a/docs/guide/build.md +++ b/docs/guide/build.md @@ -118,24 +118,21 @@ During build, all you need to do is to specify multiple `.html` files as entry p ```js twoslash [vite.config.js] import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { defineConfig } from 'vite' -const __dirname = dirname(fileURLToPath(import.meta.url)) - export default defineConfig({ build: { rolldownOptions: { input: { - main: resolve(__dirname, 'index.html'), - nested: resolve(__dirname, 'nested/index.html'), + main: resolve(import.meta.dirname, 'index.html'), + nested: resolve(import.meta.dirname, 'nested/index.html'), }, }, }, }) ``` -If you specify a different root, remember that `__dirname` will still be the folder of your `vite.config.js` file when resolving the input paths. Therefore, you will need to add your `root` entry to the arguments for `resolve`. +If you specify a different root, remember that `import.meta.dirname` will still be the folder of your `vite.config.js` file when resolving the input paths. Therefore, you will need to add your `root` entry to the arguments for `resolve`. Note that for HTML files, Vite ignores the name given to the entry in the `rolldownOptions.input` object and instead respects the resolved id of the file when generating the HTML asset in the dist folder. This ensures a consistent structure with the way the dev server works. @@ -149,15 +146,12 @@ When it is time to bundle your library for distribution, use the [`build.lib` co ```js twoslash [vite.config.js (single entry)] import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { defineConfig } from 'vite' -const __dirname = dirname(fileURLToPath(import.meta.url)) - export default defineConfig({ build: { lib: { - entry: resolve(__dirname, 'lib/main.js'), + entry: resolve(import.meta.dirname, 'lib/main.js'), name: 'MyLib', // the proper extensions will be added fileName: 'my-lib', @@ -180,17 +174,14 @@ export default defineConfig({ ```js twoslash [vite.config.js (multiple entries)] import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { defineConfig } from 'vite' -const __dirname = dirname(fileURLToPath(import.meta.url)) - export default defineConfig({ build: { lib: { entry: { - 'my-lib': resolve(__dirname, 'lib/main.js'), - secondary: resolve(__dirname, 'lib/secondary.js'), + 'my-lib': resolve(import.meta.dirname, 'lib/main.js'), + secondary: resolve(import.meta.dirname, 'lib/secondary.js'), }, name: 'MyLib', }, diff --git a/docs/guide/ssr.md b/docs/guide/ssr.md index 00190cfa9b281a..85c2569a86a219 100644 --- a/docs/guide/ssr.md +++ b/docs/guide/ssr.md @@ -68,12 +68,9 @@ When building an SSR app, you likely want to have full control over your main se ```js{15-18} twoslash [server.js] import fs from 'node:fs' import path from 'node:path' -import { fileURLToPath } from 'node:url' import express from 'express' import { createServer as createViteServer } from 'vite' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - async function createServer() { const app = express() @@ -111,7 +108,6 @@ The next step is implementing the `*` handler to serve server-rendered HTML: // @noErrors import fs from 'node:fs' import path from 'node:path' -import { fileURLToPath } from 'node:url' /** @type {import('express').Express} */ var app @@ -125,7 +121,7 @@ app.use('*all', async (req, res, next) => { try { // 1. Read index.html let template = fs.readFileSync( - path.resolve(__dirname, 'index.html'), + path.resolve(import.meta.dirname, 'index.html'), 'utf-8', ) diff --git a/packages/create-vite/__tests__/cli.spec.ts b/packages/create-vite/__tests__/cli.spec.ts index a8739e9ec23ed5..2fae4c0df9d659 100644 --- a/packages/create-vite/__tests__/cli.spec.ts +++ b/packages/create-vite/__tests__/cli.spec.ts @@ -4,11 +4,15 @@ import type { SyncOptions } from 'execa' import { execaCommandSync } from 'execa' import { afterEach, beforeAll, expect, test } from 'vitest' -const CLI_PATH = path.join(__dirname, '..') +const CLI_PATH = path.join(import.meta.dirname, '..') const projectName = 'test-app' -const genPath = path.join(__dirname, projectName) -const genPathWithSubfolder = path.join(__dirname, 'subfolder', projectName) +const genPath = path.join(import.meta.dirname, projectName) +const genPathWithSubfolder = path.join( + import.meta.dirname, + 'subfolder', + projectName, +) const run = (args: string[], options?: SyncOptions) => { return execaCommandSync(`node ${CLI_PATH} ${args.join(' ')}`, { @@ -89,14 +93,16 @@ test('prompts for the framework on supplying an invalid template', () => { test('asks to overwrite non-empty target directory', () => { createNonEmptyDir() - const { stdout } = run([projectName, '--interactive'], { cwd: __dirname }) + const { stdout } = run([projectName, '--interactive'], { + cwd: import.meta.dirname, + }) expect(stdout).toContain(`Target directory "${projectName}" is not empty.`) }) test('asks to overwrite non-empty target directory with subfolder', () => { createNonEmptyDir(genPathWithSubfolder) const { stdout } = run([`subfolder/${projectName}`, '--interactive'], { - cwd: __dirname, + cwd: import.meta.dirname, }) expect(stdout).toContain( `Target directory "subfolder/${projectName}" is not empty.`, @@ -120,7 +126,7 @@ test('successfully scaffolds a project based on vue starter template', () => { '--no-rolldown', ], { - cwd: __dirname, + cwd: import.meta.dirname, }, ) const generatedFiles = fs.readdirSync(genPath).sort() @@ -141,7 +147,7 @@ test('successfully scaffolds a project with subfolder based on react starter tem '--no-rolldown', ], { - cwd: __dirname, + cwd: import.meta.dirname, }, ) const generatedFiles = fs.readdirSync(genPathWithSubfolder).sort() @@ -153,7 +159,7 @@ test('successfully scaffolds a project with subfolder based on react starter tem test('successfully scaffolds a project based on react-compiler-ts starter template', () => { const { stdout } = run([projectName, '--template', 'react-compiler-ts'], { - cwd: __dirname, + cwd: import.meta.dirname, }) const configFile = fs.readFileSync( path.join(genPath, 'vite.config.ts'), @@ -183,7 +189,7 @@ test('works with the -t alias', () => { '--no-rolldown', ], { - cwd: __dirname, + cwd: import.meta.dirname, }, ) const generatedFiles = fs.readdirSync(genPath).sort() @@ -209,20 +215,20 @@ test('skip prompts when --no-interactive is passed', () => { }) test('return help usage how to use create-vite', () => { - const { stdout } = run(['--help'], { cwd: __dirname }) + const { stdout } = run(['--help'], { cwd: import.meta.dirname }) const message = 'Usage: create-vite [OPTION]... [DIRECTORY]' expect(stdout).toContain(message) }) test('return help usage how to use create-vite with -h alias', () => { - const { stdout } = run(['--h'], { cwd: __dirname }) + const { stdout } = run(['--h'], { cwd: import.meta.dirname }) const message = 'Usage: create-vite [OPTION]... [DIRECTORY]' expect(stdout).toContain(message) }) test('sets index.html title to project name', () => { const { stdout } = run([projectName, '--template', 'react'], { - cwd: __dirname, + cwd: import.meta.dirname, }) const indexHtmlPath = path.join(genPath, 'index.html') @@ -234,7 +240,7 @@ test('sets index.html title to project name', () => { test('accepts immediate flag', () => { const { stdout } = run([projectName, '--template', 'vue', '--immediate'], { - cwd: __dirname, + cwd: import.meta.dirname, }) expect(stdout).not.toContain('Install and start now?') expect(stdout).toContain(`Scaffolding project in ${genPath}`) @@ -243,7 +249,7 @@ test('accepts immediate flag', () => { test('accepts immediate flag and skips install prompt', () => { const { stdout } = run([projectName, '--template', 'vue', '--no-immediate'], { - cwd: __dirname, + cwd: import.meta.dirname, }) expect(stdout).not.toContain('Install and start now?') expect(stdout).not.toContain('Installing dependencies') diff --git a/packages/plugin-legacy/src/__tests__/readme.spec.ts b/packages/plugin-legacy/src/__tests__/readme.spec.ts index e74c428dc628e8..c332483a19e058 100644 --- a/packages/plugin-legacy/src/__tests__/readme.spec.ts +++ b/packages/plugin-legacy/src/__tests__/readme.spec.ts @@ -5,7 +5,7 @@ import { cspHashes } from '..' test('CSP hashes in README.md should be correct', () => { const readme = fs.readFileSync( - path.resolve(__dirname, '../../README.md'), + path.resolve(import.meta.dirname, '../../README.md'), 'utf-8', ) const hashesInDoc = [...readme.matchAll(/`sha256-(.+)`/g)].map( diff --git a/packages/vite/rolldown.config.ts b/packages/vite/rolldown.config.ts index abb6bb6f98c3d0..57a6f374093122 100644 --- a/packages/vite/rolldown.config.ts +++ b/packages/vite/rolldown.config.ts @@ -1,39 +1,39 @@ import { readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { fileURLToPath } from 'node:url' import MagicString from 'magic-string' import type { Plugin } from 'rolldown' import { defineConfig } from 'rolldown' import { init, parse } from 'es-module-lexer' import licensePlugin from './rollupLicensePlugin' +// eslint-disable-next-line n/no-unsupported-features/node-builtins +const dirname = import.meta.dirname const pkg = JSON.parse( readFileSync(new URL('./package.json', import.meta.url)).toString(), ) -const __dirname = fileURLToPath(new URL('.', import.meta.url)) const disableSourceMap = !!process.env.DEBUG_DISABLE_SOURCE_MAP const envConfig = defineConfig({ - input: path.resolve(__dirname, 'src/client/env.ts'), + input: path.resolve(dirname, 'src/client/env.ts'), platform: 'browser', transform: { target: 'es2020', }, output: { - dir: path.resolve(__dirname, 'dist'), + dir: path.resolve(dirname, 'dist'), entryFileNames: 'client/env.mjs', }, }) const clientConfig = defineConfig({ - input: path.resolve(__dirname, 'src/client/client.ts'), + input: path.resolve(dirname, 'src/client/client.ts'), platform: 'browser', transform: { target: 'es2020', }, external: ['@vite/env'], output: { - dir: path.resolve(__dirname, 'dist'), + dir: path.resolve(dirname, 'dist'), entryFileNames: 'client/client.mjs', }, }) @@ -72,9 +72,9 @@ const sharedNodeOptions = defineConfig({ const nodeConfig = defineConfig({ ...sharedNodeOptions, input: { - index: path.resolve(__dirname, 'src/node/index.ts'), - cli: path.resolve(__dirname, 'src/node/cli.ts'), - internal: path.resolve(__dirname, 'src/node/internalIndex.ts'), + index: path.resolve(dirname, 'src/node/index.ts'), + cli: path.resolve(dirname, 'src/node/cli.ts'), + internal: path.resolve(dirname, 'src/node/internalIndex.ts'), }, external: [ /^vite\//, @@ -124,7 +124,7 @@ const nodeConfig = defineConfig({ }), buildTimeImportMetaUrlPlugin(), licensePlugin( - path.resolve(__dirname, 'LICENSE.md'), + path.resolve(dirname, 'LICENSE.md'), 'Vite core license', 'Vite', ), @@ -137,7 +137,7 @@ const nodeConfig = defineConfig({ const moduleRunnerConfig = defineConfig({ ...sharedNodeOptions, input: { - 'module-runner': path.resolve(__dirname, 'src/module-runner/index.ts'), + 'module-runner': path.resolve(dirname, 'src/module-runner/index.ts'), }, external: [ 'fsevents', @@ -302,7 +302,7 @@ function buildTimeImportMetaUrlPlugin(): Plugin { code: 'import.meta.url', }, async handler(code, id) { - const relativeId = path.relative(__dirname, id).replaceAll('\\', '/') + const relativeId = path.relative(dirname, id).replaceAll('\\', '/') // only replace import.meta.url in src/ if (!relativeId.startsWith('src/')) return diff --git a/packages/vite/src/node/__tests__/build.spec.ts b/packages/vite/src/node/__tests__/build.spec.ts index c45d14ae6a50c1..a1406f33ddbfae 100644 --- a/packages/vite/src/node/__tests__/build.spec.ts +++ b/packages/vite/src/node/__tests__/build.spec.ts @@ -1,5 +1,4 @@ import { basename, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { stripVTControlCharacters } from 'node:util' import fsp from 'node:fs/promises' import colors from 'picocolors' @@ -24,7 +23,7 @@ import type { Logger } from '../logger' import { createLogger } from '../logger' import { BuildEnvironment, resolveConfig } from '..' -const __dirname = resolve(fileURLToPath(import.meta.url), '..') +const dirname = import.meta.dirname type FormatsToFileNames = [LibraryFormats, string][] @@ -32,7 +31,7 @@ describe('build', () => { test('file hash should change when css changes for dynamic entries', async () => { const buildProject = async (cssColor: string) => { return (await build({ - root: resolve(__dirname, 'packages/build-project'), + root: resolve(dirname, 'packages/build-project'), logLevel: 'silent', build: { write: false, @@ -85,7 +84,7 @@ describe('build', () => { test('file hash should change when pure css chunk changes', async () => { const buildProject = async (cssColor: string) => { return (await build({ - root: resolve(__dirname, 'packages/build-project'), + root: resolve(dirname, 'packages/build-project'), logLevel: 'silent', build: { write: false, @@ -157,7 +156,7 @@ describe('build', () => { async ([stringify, namedExports]) => { const esBundle = (await build({ mode: 'development', - root: resolve(__dirname, 'packages/build-project'), + root: resolve(dirname, 'packages/build-project'), logLevel: 'silent', json: { stringify, namedExports }, build: { @@ -363,7 +362,7 @@ describe('resolveLibFilename', () => { }, 'es', 'myLib', - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ) expect(filename).toBe('custom-filename-function.es.js') @@ -377,7 +376,7 @@ describe('resolveLibFilename', () => { }, 'es', 'myLib', - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ) expect(filename).toBe('custom-filename.mjs') @@ -390,7 +389,7 @@ describe('resolveLibFilename', () => { }, 'es', 'myLib', - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ) expect(filename).toBe('mylib.mjs') @@ -404,7 +403,7 @@ describe('resolveLibFilename', () => { }, 'es', 'myLib', - resolve(__dirname, 'packages/noname'), + resolve(dirname, 'packages/noname'), ) expect(filename).toBe('custom-filename.mjs') @@ -417,7 +416,7 @@ describe('resolveLibFilename', () => { }, 'es', 'myLib', - resolve(__dirname, 'packages/noname'), + resolve(dirname, 'packages/noname'), ) expect(filename).toBe('named-testing-package.mjs') }) @@ -435,7 +434,7 @@ describe('resolveLibFilename', () => { baseLibOptions, format, 'myLib', - resolve(__dirname, 'packages/noname'), + resolve(dirname, 'packages/noname'), ) expect(filename).toBe(expectedFilename) @@ -455,7 +454,7 @@ describe('resolveLibFilename', () => { baseLibOptions, format, 'myLib', - resolve(__dirname, 'packages/module'), + resolve(dirname, 'packages/module'), ) expect(expectedFilename).toBe(filename) @@ -475,7 +474,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -498,7 +497,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -520,7 +519,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -538,7 +537,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -558,7 +557,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -577,7 +576,7 @@ describe('resolveLibFilename', () => { libOptions, 'es', entryAlias, - resolve(__dirname, 'packages/name'), + resolve(dirname, 'packages/name'), ), ) @@ -683,7 +682,7 @@ describe('resolveBuildOutputs', () => { test('ssrEmitAssets', async () => { const result = await build({ - root: resolve(__dirname, 'fixtures/emit-assets'), + root: resolve(dirname, 'fixtures/emit-assets'), logLevel: 'silent', build: { ssr: true, @@ -709,7 +708,7 @@ describe('resolveBuildOutputs', () => { test('emitAssets', async () => { const builder = await createBuilder({ - root: resolve(__dirname, 'fixtures/emit-assets'), + root: resolve(dirname, 'fixtures/emit-assets'), logLevel: 'warn', environments: { ssr: { @@ -740,7 +739,7 @@ describe('resolveBuildOutputs', () => { test('ssr builtin', async () => { const builder = await createBuilder({ - root: resolve(__dirname, 'fixtures/dynamic-import'), + root: resolve(dirname, 'fixtures/dynamic-import'), logLevel: 'warn', environments: { ssr: { @@ -761,7 +760,7 @@ describe('resolveBuildOutputs', () => { test('ssr custom', async () => { const builder = await createBuilder({ - root: resolve(__dirname, 'fixtures/dynamic-import'), + root: resolve(dirname, 'fixtures/dynamic-import'), logLevel: 'warn', environments: { custom: { @@ -784,7 +783,7 @@ describe('resolveBuildOutputs', () => { test('default sharedConfigBuild true on build api', async () => { let counter = 0 await build({ - root: resolve(__dirname, 'fixtures/emit-assets'), + root: resolve(dirname, 'fixtures/emit-assets'), logLevel: 'warn', build: { ssr: true, @@ -809,7 +808,7 @@ test('default sharedConfigBuild true on build api', async () => { test.for([true, false])( 'minify per environment (builder.sharedPlugins: %s)', async (sharedPlugins) => { - const root = resolve(__dirname, 'fixtures/shared-plugins/minify') + const root = resolve(dirname, 'fixtures/shared-plugins/minify') const builder = await createBuilder({ root, logLevel: 'warn', @@ -866,7 +865,7 @@ test.for([true, false])( ) test('sharedConfigBuild and emitAssets', async () => { - const root = resolve(__dirname, 'fixtures/shared-config-build/emitAssets') + const root = resolve(dirname, 'fixtures/shared-config-build/emitAssets') const builder = await createBuilder({ root, logLevel: 'warn', @@ -935,7 +934,7 @@ test('sharedConfigBuild and emitAssets', async () => { test.skip('adjust worker build error for worker.format', async () => { try { await build({ - root: resolve(__dirname, 'fixtures/worker-dynamic'), + root: resolve(dirname, 'fixtures/worker-dynamic'), build: { rollupOptions: { input: { @@ -964,7 +963,7 @@ describe('onRollupLog', () => { options?: Pick, ) => { await build({ - root: resolve(__dirname, 'packages/build-project'), + root: resolve(dirname, 'packages/build-project'), logLevel: 'info', build: { write: false, @@ -1108,7 +1107,7 @@ describe('onRollupLog', () => { test('watch rebuild manifest', async (ctx) => { // this doesn't actually test watch rebuild // but it simulates something similar by running two builds for the same environment - const root = resolve(__dirname, 'fixtures/watch-rebuild-manifest') + const root = resolve(dirname, 'fixtures/watch-rebuild-manifest') const builder = await createBuilder({ root, logLevel: 'error', diff --git a/packages/vite/src/node/__tests__/config.spec.ts b/packages/vite/src/node/__tests__/config.spec.ts index b532733c7ec35e..e3488cc253288e 100644 --- a/packages/vite/src/node/__tests__/config.spec.ts +++ b/packages/vite/src/node/__tests__/config.spec.ts @@ -1034,7 +1034,7 @@ test('preTransformRequests', async () => { }) describe('loadConfigFromFile', () => { - const fixtures = path.resolve(__dirname, './fixtures/config') + const fixtures = path.resolve(import.meta.dirname, './fixtures/config') describe('load default files', () => { const root = path.resolve(fixtures, './loadConfigFromFile') diff --git a/packages/vite/src/node/__tests__/dev.spec.ts b/packages/vite/src/node/__tests__/dev.spec.ts index 8cc6f16b304bb1..11dc0fd1883cfd 100644 --- a/packages/vite/src/node/__tests__/dev.spec.ts +++ b/packages/vite/src/node/__tests__/dev.spec.ts @@ -38,7 +38,7 @@ describe('the dev server', () => { const { promise, resolve } = promiseWithResolvers() server = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'error', server: { strictPort: true, diff --git a/packages/vite/src/node/__tests__/env.spec.ts b/packages/vite/src/node/__tests__/env.spec.ts index 36fbaa2d8172d0..d553b9389c14be 100644 --- a/packages/vite/src/node/__tests__/env.spec.ts +++ b/packages/vite/src/node/__tests__/env.spec.ts @@ -1,13 +1,12 @@ import { join } from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, test } from 'vitest' import { loadEnv } from '../env' -const __dirname = fileURLToPath(new URL('.', import.meta.url)) +const dirname = import.meta.dirname describe('loadEnv', () => { test('basic', () => { - expect(loadEnv('development', join(__dirname, './env'))) + expect(loadEnv('development', join(dirname, './env'))) .toMatchInlineSnapshot(` { "VITE_APP_BASE_ROUTE": "/", @@ -20,7 +19,7 @@ describe('loadEnv', () => { }) test('specific prefix', () => { - expect(loadEnv('development', join(__dirname, './env'), 'VVITE')) + expect(loadEnv('development', join(dirname, './env'), 'VVITE')) .toMatchInlineSnapshot(` { "VVITE_A": "A", @@ -30,7 +29,7 @@ describe('loadEnv', () => { }) test('override', () => { - expect(loadEnv('production', join(__dirname, './env'))) + expect(loadEnv('production', join(dirname, './env'))) .toMatchInlineSnapshot(` { "VITE_APP_BASE_ROUTE": "/app/", @@ -40,7 +39,7 @@ describe('loadEnv', () => { }) test('override 2', () => { - expect(loadEnv('development2', join(__dirname, './env'))) + expect(loadEnv('development2', join(dirname, './env'))) .toMatchInlineSnapshot(` { "VITE_APP_BASE_ROUTE": "source", @@ -51,28 +50,27 @@ describe('loadEnv', () => { }) test('VITE_USER_NODE_ENV', () => { - loadEnv('development', join(__dirname, './env')) + loadEnv('development', join(dirname, './env')) expect(process.env.VITE_USER_NODE_ENV).toEqual(undefined) }) test('VITE_USER_NODE_ENV for dev behaviour in build', () => { const _nodeEnv = process.env.NODE_ENV process.env.NODE_ENV = 'production' - loadEnv('testing', join(__dirname, './env')) + loadEnv('testing', join(dirname, './env')) expect(process.env.VITE_USER_NODE_ENV).toEqual('development') process.env.NODE_ENV = _nodeEnv }) test('Already exists VITE_USER_NODE_ENV', () => { process.env.VITE_USER_NODE_ENV = 'test' - loadEnv('development', join(__dirname, './env')) + loadEnv('development', join(dirname, './env')) expect(process.env.VITE_USER_NODE_ENV).toEqual('test') }) test('prioritize existing process.env', () => { process.env.VITE_ENV_TEST_ENV = 'EXIST' - expect(loadEnv('existing', join(__dirname, './env'))) - .toMatchInlineSnapshot(` + expect(loadEnv('existing', join(dirname, './env'))).toMatchInlineSnapshot(` { "VITE_APP_BASE_ROUTE": "/", "VITE_APP_BASE_URL": "/", diff --git a/packages/vite/src/node/__tests__/http.spec.ts b/packages/vite/src/node/__tests__/http.spec.ts index 08cba2eded190f..d38ffe3e31f1b2 100644 --- a/packages/vite/src/node/__tests__/http.spec.ts +++ b/packages/vite/src/node/__tests__/http.spec.ts @@ -47,7 +47,7 @@ describe('port detection', () => { ) viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, strictPort: false, ws: false }, }) @@ -70,7 +70,7 @@ describe('port detection', () => { ) viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, strictPort: false, ws: false }, }) @@ -89,7 +89,7 @@ describe('port detection', () => { ) viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, strictPort: false, ws: false }, }) @@ -113,7 +113,7 @@ describe('port detection', () => { await using _blockingServer = blockingServer viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, strictPort: false, ws: false }, }) @@ -140,7 +140,7 @@ describe('port detection', () => { ) viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, @@ -164,7 +164,7 @@ describe('port detection', () => { ) viteServer = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'silent', server: { port: BASE_PORT, strictPort: true, ws: false }, }) diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index dc667e68e21309..2deda4e3711072 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -1,5 +1,4 @@ import path from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, test } from 'vitest' import { resolveConfig } from '../../config' import type { InlineConfig } from '../../config' @@ -14,7 +13,7 @@ import { } from '../../plugins/css' import { PartialEnvironment } from '../../baseEnvironment' -const __dirname = path.resolve(fileURLToPath(import.meta.url), '..') +const dirname = import.meta.dirname describe('search css url function', () => { test('some spaces before it', () => { @@ -421,7 +420,7 @@ describe('resolveLibCssFilename', () => { { entry: 'mylib.js', }, - path.resolve(__dirname, '../packages/name'), + path.resolve(dirname, '../packages/name'), ) expect(filename).toBe('mylib.css') }) @@ -432,7 +431,7 @@ describe('resolveLibCssFilename', () => { entry: 'mylib.js', cssFileName: 'style', }, - path.resolve(__dirname, '../packages/noname'), + path.resolve(dirname, '../packages/noname'), ) expect(filename).toBe('style.css') }) @@ -443,7 +442,7 @@ describe('resolveLibCssFilename', () => { entry: 'mylib.js', fileName: 'custom-name', }, - path.resolve(__dirname, '../packages/name'), + path.resolve(dirname, '../packages/name'), ) expect(filename).toBe('custom-name.css') }) @@ -454,7 +453,7 @@ describe('resolveLibCssFilename', () => { entry: ['mylib.js', 'mylib2.js'], fileName: 'custom-name', }, - path.resolve(__dirname, '../packages/name'), + path.resolve(dirname, '../packages/name'), ) expect(filename).toBe('custom-name.css') }) diff --git a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.spec.ts b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.spec.ts index 8a67660258386a..d9aeb9c24bea17 100644 --- a/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/dynamicImportVar/parse.spec.ts @@ -1,22 +1,21 @@ import { resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { transformDynamicImport } from '../../../plugins/dynamicImportVars' import { normalizePath } from '../../../utils' import { isWindows } from '../../../../shared/utils' -const __dirname = resolve(fileURLToPath(import.meta.url), '..') +const dirname = import.meta.dirname async function run(input: string) { const { glob, rawPattern } = (await transformDynamicImport( input, - normalizePath(resolve(__dirname, 'index.js')), + normalizePath(resolve(dirname, 'index.js')), (id) => id - .replace('@', resolve(__dirname, './mods/')) - .replace('#', resolve(__dirname, '../../')), - __dirname, + .replace('@', resolve(dirname, './mods/')) + .replace('#', resolve(dirname, '../../')), + dirname, )) || {} return `__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)` } diff --git a/packages/vite/src/node/__tests__/plugins/importGlob/fixture.spec.ts b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.spec.ts index 8276ddc8e1b553..74736f7dc640ac 100644 --- a/packages/vite/src/node/__tests__/plugins/importGlob/fixture.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/importGlob/fixture.spec.ts @@ -1,18 +1,15 @@ -import { dirname, resolve } from 'node:path' +import { resolve } from 'node:path' import { promises as fs } from 'node:fs' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { transformGlobImport } from '../../../plugins/importMetaGlob' import { transformWithEsbuild } from '../../../plugins/esbuild' -const __dirname = resolve(dirname(fileURLToPath(import.meta.url))) - describe('fixture', async () => { const resolveId = (id: string) => id - const root = __dirname + const root = import.meta.dirname it('transform', async () => { - const id = resolve(__dirname, './fixture-a/index.ts') + const id = resolve(import.meta.dirname, './fixture-a/index.ts') const code = ( await transformWithEsbuild(await fs.readFile(id, 'utf-8'), id) ).code @@ -41,7 +38,7 @@ describe('fixture', async () => { }) it('virtual modules', async () => { - const root = resolve(__dirname, './fixture-a') + const root = resolve(import.meta.dirname, './fixture-a') const code = [ "import.meta.glob('/modules/*.ts')", "import.meta.glob(['/../fixture-b/*.ts'])", @@ -69,7 +66,7 @@ describe('fixture', async () => { }) it('transform with restoreQueryExtension', async () => { - const id = resolve(__dirname, './fixture-a/index.ts') + const id = resolve(import.meta.dirname, './fixture-a/index.ts') const code = ( await transformWithEsbuild(await fs.readFile(id, 'utf-8'), id) ).code diff --git a/packages/vite/src/node/__tests__/plugins/terser.spec.ts b/packages/vite/src/node/__tests__/plugins/terser.spec.ts index c6838e793a131d..cd3e8e86ec0a03 100644 --- a/packages/vite/src/node/__tests__/plugins/terser.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/terser.spec.ts @@ -1,16 +1,13 @@ import { resolve } from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, test } from 'vitest' import { build } from 'vite' import type { RollupOutput } from 'rollup' import type { TerserOptions } from '../../plugins/terser' -const __dirname = resolve(fileURLToPath(import.meta.url), '..') - describe('terser', () => { const run = async (terserOptions: TerserOptions) => { const result = (await build({ - root: resolve(__dirname, '../packages/build-project'), + root: resolve(import.meta.dirname, '../packages/build-project'), logLevel: 'silent', build: { write: false, diff --git a/packages/vite/src/node/server/__tests__/search-root.spec.ts b/packages/vite/src/node/server/__tests__/search-root.spec.ts index 10dfdabc133cad..6b14f84b425feb 100644 --- a/packages/vite/src/node/server/__tests__/search-root.spec.ts +++ b/packages/vite/src/node/server/__tests__/search-root.spec.ts @@ -1,42 +1,41 @@ -import { dirname, resolve } from 'node:path' -import { fileURLToPath } from 'node:url' +import { resolve } from 'node:path' import { describe, expect, test } from 'vitest' import { searchForWorkspaceRoot } from '../searchRoot' -const __dirname = dirname(fileURLToPath(import.meta.url)) +const dirname = import.meta.dirname describe('searchForWorkspaceRoot', () => { test('lerna', () => { const resolved = searchForWorkspaceRoot( - resolve(__dirname, 'fixtures/lerna/nested'), + resolve(dirname, 'fixtures/lerna/nested'), ) - expect(resolved).toBe(resolve(__dirname, 'fixtures/lerna')) + expect(resolved).toBe(resolve(dirname, 'fixtures/lerna')) }) test('pnpm', () => { const resolved = searchForWorkspaceRoot( - resolve(__dirname, 'fixtures/pnpm/nested'), + resolve(dirname, 'fixtures/pnpm/nested'), ) - expect(resolved).toBe(resolve(__dirname, 'fixtures/pnpm')) + expect(resolved).toBe(resolve(dirname, 'fixtures/pnpm')) }) test('yarn', () => { const resolved = searchForWorkspaceRoot( - resolve(__dirname, 'fixtures/yarn/nested'), + resolve(dirname, 'fixtures/yarn/nested'), ) - expect(resolved).toBe(resolve(__dirname, 'fixtures/yarn')) + expect(resolved).toBe(resolve(dirname, 'fixtures/yarn')) }) test('yarn at root', () => { - const resolved = searchForWorkspaceRoot(resolve(__dirname, 'fixtures/yarn')) - expect(resolved).toBe(resolve(__dirname, 'fixtures/yarn')) + const resolved = searchForWorkspaceRoot(resolve(dirname, 'fixtures/yarn')) + expect(resolved).toBe(resolve(dirname, 'fixtures/yarn')) }) test('none', () => { const resolved = searchForWorkspaceRoot( - resolve(__dirname, 'fixtures/none/nested'), + resolve(dirname, 'fixtures/none/nested'), ) // resolved to vite repo's root - expect(resolved).toBe(resolve(__dirname, '../../../../../..')) + expect(resolved).toBe(resolve(dirname, '../../../../../..')) }) }) diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.invoke.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.invoke.spec.ts index 33a9ed9130f5a1..b511365087f1fb 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.invoke.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.invoke.spec.ts @@ -26,7 +26,7 @@ describe('running module runner inside a worker and using the ModuleRunnerTransp worker.on('error', reject) }) server = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'error', server: { middlewareMode: true, diff --git a/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.spec.ts b/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.spec.ts index 5da9d2016343c0..25c388034ccd46 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.spec.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/server-worker-runner.spec.ts @@ -71,7 +71,7 @@ describe('running module runner inside a worker', () => { worker.on('error', reject) }) const server = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'error', server: { middlewareMode: true, diff --git a/packages/vite/src/node/ssr/runtime/__tests__/utils.ts b/packages/vite/src/node/ssr/runtime/__tests__/utils.ts index 1ed4b6d1c9d641..8ebe6708224d9c 100644 --- a/packages/vite/src/node/ssr/runtime/__tests__/utils.ts +++ b/packages/vite/src/node/ssr/runtime/__tests__/utils.ts @@ -36,7 +36,7 @@ export async function createModuleRunnerTester( globalThis.__HMR__ = {} t.server = await createServer({ - root: __dirname, + root: import.meta.dirname, logLevel: 'error', server: { middlewareMode: true, diff --git a/playground/alias/vite.config.js b/playground/alias/vite.config.js index 3585320b88f141..56f128c2a3d57e 100644 --- a/playground/alias/vite.config.js +++ b/playground/alias/vite.config.js @@ -7,16 +7,16 @@ const require = module.createRequire(import.meta.url) export default defineConfig({ resolve: { alias: [ - { find: 'fs', replacement: path.resolve(__dirname, 'test.js') }, - { find: 'fs-dir', replacement: path.resolve(__dirname, 'dir') }, + { find: 'fs', replacement: path.resolve(import.meta.dirname, 'test.js') }, + { find: 'fs-dir', replacement: path.resolve(import.meta.dirname, 'dir') }, { find: 'dep', replacement: '@vitejs/test-resolve-linked' }, { find: /^regex\/(.*)/, - replacement: `${path.resolve(__dirname, 'dir')}/$1`, + replacement: `${path.resolve(import.meta.dirname, 'dir')}/$1`, }, - { find: '/@', replacement: path.resolve(__dirname, 'dir') }, + { find: '/@', replacement: path.resolve(import.meta.dirname, 'dir') }, // aliasing a pattern that conflicts with url schemes - { find: /^\/\//, replacement: path.join(__dirname, 'dir/') }, + { find: /^\/\//, replacement: path.join(import.meta.dirname, 'dir/') }, // aliasing an optimized dep { find: 'vue', replacement: 'vue/dist/vue.esm-bundler.js' }, // aliasing an optimized dep to absolute URL @@ -28,7 +28,7 @@ export default defineConfig({ { find: 'foo', replacement: 'vue' }, { find: 'custom-resolver', - replacement: path.resolve(__dirname, 'test.js'), + replacement: path.resolve(import.meta.dirname, 'test.js'), customResolver(id) { return id.replace('test.js', 'customResolver.js') }, diff --git a/playground/assets/vite.config.js b/playground/assets/vite.config.js index e0ba18d5e69567..9051e837ddb366 100644 --- a/playground/assets/vite.config.js +++ b/playground/assets/vite.config.js @@ -6,8 +6,8 @@ export default defineConfig({ publicDir: 'static', resolve: { alias: { - '@': path.resolve(__dirname, 'nested'), - fragment: path.resolve(__dirname, 'nested/fragment-bg.svg'), + '@': path.resolve(import.meta.dirname, 'nested'), + fragment: path.resolve(import.meta.dirname, 'nested/fragment-bg.svg'), }, }, assetsInclude: ['**/*.unknown'], diff --git a/playground/backend-integration/vite.config.js b/playground/backend-integration/vite.config.js index 7560c31541ac22..d2a8a868471f78 100644 --- a/playground/backend-integration/vite.config.js +++ b/playground/backend-integration/vite.config.js @@ -10,7 +10,7 @@ function BackendIntegrationExample() { return { name: 'backend-integration', config() { - const projectRoot = __dirname + const projectRoot = import.meta.dirname const sourceCodeDir = path.join(projectRoot, 'frontend') const root = path.join(sourceCodeDir, 'entrypoints') const outDir = path.relative(root, path.join(projectRoot, 'dist/dev')) @@ -22,10 +22,10 @@ function BackendIntegrationExample() { }).map((filename) => [path.relative(root, filename), filename]) entrypoints.push(['tailwindcss-colors', 'tailwindcss/colors.js']) - entrypoints.push(['bar.css', path.resolve(__dirname, './dir/foo.css')]) + entrypoints.push(['bar.css', path.resolve(projectRoot, './dir/foo.css')]) entrypoints.push([ 'bar.custom', - path.resolve(__dirname, './dir/custom.css'), + path.resolve(projectRoot, './dir/custom.css'), ]) return { diff --git a/playground/csp/vite.config.js b/playground/csp/vite.config.js index 84d6d92ba0d0bb..6b255abdd30df8 100644 --- a/playground/csp/vite.config.js +++ b/playground/csp/vite.config.js @@ -1,11 +1,8 @@ import fs from 'node:fs/promises' -import url from 'node:url' import path from 'node:path' import crypto from 'node:crypto' import { defineConfig } from 'vite' -const __dirname = path.dirname(url.fileURLToPath(import.meta.url)) - const noncePlaceholder = '#$NONCE$#' const createNonce = () => crypto.randomBytes(16).toString('base64') @@ -28,7 +25,10 @@ const setNonceHeader = (res, nonce) => { const createMiddleware = (file, transform) => async (req, res) => { const nonce = createNonce() setNonceHeader(res, nonce) - const content = await fs.readFile(path.join(__dirname, file), 'utf-8') + const content = await fs.readFile( + path.join(import.meta.dirname, file), + 'utf-8', + ) const transformedContent = await transform(content, req.originalUrl) res.setHeader('Content-Type', 'text/html') res.end(transformedContent.replaceAll(noncePlaceholder, nonce)) diff --git a/playground/css-codesplit-cjs/vite.config.js b/playground/css-codesplit-cjs/vite.config.js index 0c8a0cbf562a4b..243476ae5bdcb0 100644 --- a/playground/css-codesplit-cjs/vite.config.js +++ b/playground/css-codesplit-cjs/vite.config.js @@ -7,8 +7,8 @@ export default defineConfig({ manifest: true, rollupOptions: { input: { - main: resolve(__dirname, './index.html'), - other: resolve(__dirname, './other.js'), + main: resolve(import.meta.dirname, './index.html'), + other: resolve(import.meta.dirname, './other.js'), }, treeshake: false, output: { diff --git a/playground/css-codesplit/vite.config.js b/playground/css-codesplit/vite.config.js index 45d40d74dbc0b9..064f5d8487371b 100644 --- a/playground/css-codesplit/vite.config.js +++ b/playground/css-codesplit/vite.config.js @@ -1,16 +1,18 @@ import { resolve } from 'node:path' import { defineConfig } from 'vite' +const dirname = import.meta.dirname + export default defineConfig({ build: { manifest: true, rollupOptions: { input: { - main: resolve(__dirname, './index.html'), - other: resolve(__dirname, './other.js'), - style2: resolve(__dirname, './style2.js'), - 'shared-css-with-js': resolve(__dirname, 'shared-css-with-js.html'), - 'shared-css-no-js': resolve(__dirname, 'shared-css-no-js.html'), + main: resolve(dirname, './index.html'), + other: resolve(dirname, './other.js'), + style2: resolve(dirname, './style2.js'), + 'shared-css-with-js': resolve(dirname, 'shared-css-with-js.html'), + 'shared-css-no-js': resolve(dirname, 'shared-css-no-js.html'), }, output: { // manualChunks(id) { diff --git a/playground/css-lightningcss-proxy/server.js b/playground/css-lightningcss-proxy/server.js index 63bc4aa2b1de5c..c50a423b72b43b 100644 --- a/playground/css-lightningcss-proxy/server.js +++ b/playground/css-lightningcss-proxy/server.js @@ -3,7 +3,6 @@ import path from 'node:path' import { fileURLToPath } from 'node:url' import express from 'express' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) const isTest = process.env.VITEST const DYNAMIC_STYLES = ` @@ -15,7 +14,7 @@ const DYNAMIC_STYLES = ` ` export async function createServer(root = process.cwd(), hmrPort) { - const resolve = (p) => path.resolve(__dirname, p) + const resolve = (p) => path.resolve(import.meta.dirname, p) const app = express() diff --git a/playground/css-lightningcss/vite.config.js b/playground/css-lightningcss/vite.config.js index fbefa0d4d4b99f..116489f5189919 100644 --- a/playground/css-lightningcss/vite.config.js +++ b/playground/css-lightningcss/vite.config.js @@ -7,7 +7,7 @@ export default defineConfig({ }, resolve: { alias: { - '@': path.resolve(__dirname, 'nested'), + '@': path.resolve(import.meta.dirname, 'nested'), }, }, build: { diff --git a/playground/css-no-codesplit/vite.config.js b/playground/css-no-codesplit/vite.config.js index f48d875832b928..0607cf2600bb2c 100644 --- a/playground/css-no-codesplit/vite.config.js +++ b/playground/css-no-codesplit/vite.config.js @@ -6,8 +6,8 @@ export default defineConfig({ cssCodeSplit: false, rollupOptions: { input: { - index: resolve(__dirname, './index.html'), - sub: resolve(__dirname, './sub.html'), + index: resolve(import.meta.dirname, './index.html'), + sub: resolve(import.meta.dirname, './sub.html'), }, }, }, diff --git a/playground/css-sourcemap/vite.config.js b/playground/css-sourcemap/vite.config.js index e51cf320ad76e1..40723e6302e0eb 100644 --- a/playground/css-sourcemap/vite.config.js +++ b/playground/css-sourcemap/vite.config.js @@ -4,7 +4,7 @@ import MagicString from 'magic-string' export default defineConfig({ resolve: { alias: { - '@': __dirname, + '@': import.meta.dirname, }, }, css: { diff --git a/playground/css/__tests__/postcss-plugins-different-dir/css-postcss-plugins-different-dir.spec.ts b/playground/css/__tests__/postcss-plugins-different-dir/css-postcss-plugins-different-dir.spec.ts index e9a8e129e10850..cd2b474ce7baf2 100644 --- a/playground/css/__tests__/postcss-plugins-different-dir/css-postcss-plugins-different-dir.spec.ts +++ b/playground/css/__tests__/postcss-plugins-different-dir/css-postcss-plugins-different-dir.spec.ts @@ -7,7 +7,7 @@ import { getBgColor, getColor, isServe, page, ports } from '~utils' test.runIf(isServe)('postcss plugins in different dir', async () => { const port = ports['css/postcss-plugins-different-dir'] const server = await createServer({ - root: path.join(__dirname, '..', '..', '..', 'tailwind'), + root: path.join(import.meta.dirname, '..', '..', '..', 'tailwind'), logLevel: 'silent', server: { port, diff --git a/playground/css/postcss-caching/css.spec.ts b/playground/css/postcss-caching/css.spec.ts index 842d2726590d31..7ff525828e8973 100644 --- a/playground/css/postcss-caching/css.spec.ts +++ b/playground/css/postcss-caching/css.spec.ts @@ -22,8 +22,8 @@ test.runIf(isServe)('postcss config', async () => { return server } - const blueAppDir = path.join(__dirname, 'blue-app') - const greenAppDir = path.join(__dirname, 'green-app') + const blueAppDir = path.join(import.meta.dirname, 'blue-app') + const greenAppDir = path.join(import.meta.dirname, 'green-app') let blueApp let greenApp try { diff --git a/playground/css/vite.config.js b/playground/css/vite.config.js index 993ed630670f56..76dc4395aeac39 100644 --- a/playground/css/vite.config.js +++ b/playground/css/vite.config.js @@ -10,6 +10,8 @@ globalThis.window = {} // @ts-expect-error refer to https://github.com/vitejs/vite/pull/11079 globalThis.location = new URL('http://localhost/') +const dirname = import.meta.dirname + export default defineConfig({ plugins: [ { @@ -41,12 +43,9 @@ export default defineConfig({ cssTarget: 'chrome61', rollupOptions: { input: { - index: path.resolve(__dirname, './index.html'), - treeshakeScoped: path.resolve( - __dirname, - './treeshake-scoped/index.html', - ), - empty: path.resolve(__dirname, './empty.css'), + index: path.resolve(dirname, './index.html'), + treeshakeScoped: path.resolve(dirname, './treeshake-scoped/index.html'), + empty: path.resolve(dirname, './empty.css'), }, output: { manualChunks(id) { @@ -64,17 +63,17 @@ export default defineConfig({ }, resolve: { alias: [ - { find: '=', replacement: __dirname }, - { find: /^=replace\/(.*)/, replacement: `${__dirname}/$1` }, - { find: 'spacefolder', replacement: __dirname + '/folder with space' }, - { find: '#alias', replacement: __dirname + '/aliased/foo.css' }, + { find: '=', replacement: dirname }, + { find: /^=replace\/(.*)/, replacement: `${dirname}/$1` }, + { find: 'spacefolder', replacement: dirname + '/folder with space' }, + { find: '#alias', replacement: dirname + '/aliased/foo.css' }, { find: '#alias?inline', - replacement: __dirname + '/aliased/foo.css?inline', + replacement: dirname + '/aliased/foo.css?inline', }, { find: '#alias-module', - replacement: __dirname + '/aliased/bar.module.css', + replacement: dirname + '/aliased/bar.module.css', }, ], }, @@ -136,7 +135,7 @@ export default defineConfig({ additionalData: `$injectedColor ?= orange`, imports: [ './options/relative-import.styl', - path.join(__dirname, 'options/absolute-import.styl'), + path.join(dirname, 'options/absolute-import.styl'), ], define: { $definedColor: new stylus.nodes.RGBA(51, 197, 255, 1), diff --git a/playground/dynamic-import-inline/vite.config.js b/playground/dynamic-import-inline/vite.config.js index ee8571ac585f40..8d25f33d0b9512 100644 --- a/playground/dynamic-import-inline/vite.config.js +++ b/playground/dynamic-import-inline/vite.config.js @@ -4,7 +4,7 @@ import { defineConfig } from 'vite' export default defineConfig({ resolve: { alias: { - '@': path.resolve(__dirname, 'alias'), + '@': path.resolve(import.meta.dirname, 'alias'), }, }, build: { diff --git a/playground/dynamic-import/vite.config.js b/playground/dynamic-import/vite.config.js index dc8ecbd8bbdfe5..ad68283310617e 100644 --- a/playground/dynamic-import/vite.config.js +++ b/playground/dynamic-import/vite.config.js @@ -2,31 +2,33 @@ import fs from 'node:fs' import path from 'node:path' import { defineConfig } from 'vite' +const dirname = import.meta.dirname + export default defineConfig({ plugins: [ { name: 'copy', writeBundle() { - fs.mkdirSync(path.resolve(__dirname, 'dist/views')) - fs.mkdirSync(path.resolve(__dirname, 'dist/files')) + fs.mkdirSync(path.resolve(dirname, 'dist/views')) + fs.mkdirSync(path.resolve(dirname, 'dist/files')) fs.copyFileSync( - path.resolve(__dirname, 'views/qux.js'), - path.resolve(__dirname, 'dist/views/qux.js'), + path.resolve(dirname, 'views/qux.js'), + path.resolve(dirname, 'dist/views/qux.js'), ) fs.copyFileSync( - path.resolve(__dirname, 'files/mxd.js'), - path.resolve(__dirname, 'dist/files/mxd.js'), + path.resolve(dirname, 'files/mxd.js'), + path.resolve(dirname, 'dist/files/mxd.js'), ) fs.copyFileSync( - path.resolve(__dirname, 'files/mxd.json'), - path.resolve(__dirname, 'dist/files/mxd.json'), + path.resolve(dirname, 'files/mxd.json'), + path.resolve(dirname, 'dist/files/mxd.json'), ) }, }, ], resolve: { alias: { - '@': path.resolve(__dirname, 'alias'), + '@': path.resolve(dirname, 'alias'), }, }, build: { diff --git a/playground/external/vite.config.js b/playground/external/vite.config.js index d79decb009ca6d..81ccd7d704edc8 100644 --- a/playground/external/vite.config.js +++ b/playground/external/vite.config.js @@ -32,7 +32,7 @@ export default defineConfig({ external: ['vue', 'slash3', 'slash5'], transform: { inject: { - require: path.resolve(__dirname, 'src/require-polyfill.js'), + require: path.resolve(import.meta.dirname, 'src/require-polyfill.js'), }, }, }, diff --git a/playground/fs-serve/__tests__/fs-serve.spec.ts b/playground/fs-serve/__tests__/fs-serve.spec.ts index a728a22fc5aff4..2cb710a269febb 100644 --- a/playground/fs-serve/__tests__/fs-serve.spec.ts +++ b/playground/fs-serve/__tests__/fs-serve.spec.ts @@ -22,8 +22,6 @@ import { viteTestUrl, } from '~utils' -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - const getViteTestIndexHtmlUrl = () => { const srcPrefix = viteTestUrl.endsWith('/') ? '' : '/' // NOTE: viteTestUrl is set lazily @@ -505,7 +503,7 @@ describe.runIf(isServe)('invalid request', () => { } const root = path - .resolve(__dirname.replace('playground', 'playground-temp'), '..') + .resolve(import.meta.dirname.replace('playground', 'playground-temp'), '..') .replace(/\\/g, '/') test('request with sendRawRequest should work', async () => { diff --git a/playground/fs-serve/root/vite.config-base.js b/playground/fs-serve/root/vite.config-base.js index 1dd2f99b9f9124..c1ca2a52841143 100644 --- a/playground/fs-serve/root/vite.config-base.js +++ b/playground/fs-serve/root/vite.config-base.js @@ -9,14 +9,14 @@ export default defineConfig({ build: { rollupOptions: { input: { - main: path.resolve(__dirname, 'src/index.html'), + main: path.resolve(import.meta.dirname, 'src/index.html'), }, }, }, server: { fs: { strict: true, - allow: [path.resolve(__dirname, 'src')], + allow: [path.resolve(import.meta.dirname, 'src')], }, hmr: { overlay: false, @@ -31,7 +31,7 @@ export default defineConfig({ }, }, define: { - ROOT: JSON.stringify(path.dirname(__dirname).replace(/\\/g, '/')), + ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')), BASE: JSON.stringify(BASE), }, plugins: [svgVirtualModulePlugin()], diff --git a/playground/fs-serve/root/vite.config-deny.js b/playground/fs-serve/root/vite.config-deny.js index 11698cef800ec3..2772d3adef93cd 100644 --- a/playground/fs-serve/root/vite.config-deny.js +++ b/playground/fs-serve/root/vite.config-deny.js @@ -6,19 +6,19 @@ export default defineConfig({ build: { rollupOptions: { input: { - main: path.resolve(__dirname, 'src/index.html'), + main: path.resolve(import.meta.dirname, 'src/index.html'), }, }, }, server: { fs: { strict: true, - allow: [path.resolve(__dirname, 'src')], + allow: [path.resolve(import.meta.dirname, 'src')], deny: ['**/deny/**'], }, }, define: { - ROOT: JSON.stringify(path.dirname(__dirname).replace(/\\/g, '/')), + ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')), }, plugins: [svgVirtualModulePlugin()], }) diff --git a/playground/fs-serve/root/vite.config.js b/playground/fs-serve/root/vite.config.js index ac4eaac97c1d61..43a192eab1cac9 100644 --- a/playground/fs-serve/root/vite.config.js +++ b/playground/fs-serve/root/vite.config.js @@ -6,14 +6,14 @@ export default defineConfig({ build: { rollupOptions: { input: { - main: path.resolve(__dirname, 'src/index.html'), + main: path.resolve(import.meta.dirname, 'src/index.html'), }, }, }, server: { fs: { strict: true, - allow: [path.resolve(__dirname, 'src')], + allow: [path.resolve(import.meta.dirname, 'src')], }, hmr: { overlay: false, @@ -28,7 +28,7 @@ export default defineConfig({ }, }, define: { - ROOT: JSON.stringify(path.dirname(__dirname).replace(/\\/g, '/')), + ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')), }, plugins: [svgVirtualModulePlugin()], }) diff --git a/playground/glob-import/__tests__/glob-import.spec.ts b/playground/glob-import/__tests__/glob-import.spec.ts index 90b973e501270a..81125143c69479 100644 --- a/playground/glob-import/__tests__/glob-import.spec.ts +++ b/playground/glob-import/__tests__/glob-import.spec.ts @@ -265,7 +265,7 @@ test('escapes special chars in globs without mangling user supplied glob suffix' // index.html has a script that loads all these glob.js files and prints the globs that returned the expected result // this test finally compares the printed output of index.js with the list of directories with special chars, // expecting that they all work - const files = await readdir(path.join(__dirname, '..', 'escape'), { + const files = await readdir(path.join(import.meta.dirname, '..', 'escape'), { withFileTypes: true, }) const expectedNames = files diff --git a/playground/glob-import/vite.config.ts b/playground/glob-import/vite.config.ts index 40779dca525d93..3f2c42961c4c32 100644 --- a/playground/glob-import/vite.config.ts +++ b/playground/glob-import/vite.config.ts @@ -3,12 +3,14 @@ import path from 'node:path' import { defineConfig } from 'vite' const escapeAliases = fs - .readdirSync(path.join(__dirname, 'escape'), { withFileTypes: true }) + .readdirSync(path.join(import.meta.dirname, 'escape'), { + withFileTypes: true, + }) .filter((f) => f.isDirectory()) .map((f) => f.name) .reduce((aliases: Record, dir) => { aliases[`@escape_${dir}_mod`] = path.resolve( - __dirname, + import.meta.dirname, `./escape/${dir}/mod`, ) return aliases @@ -33,8 +35,8 @@ export default defineConfig({ resolve: { alias: { ...escapeAliases, - '@dir': path.resolve(__dirname, './dir/'), - '#alias': path.resolve(__dirname, './imports-path/'), + '@dir': path.resolve(import.meta.dirname, './dir/'), + '#alias': path.resolve(import.meta.dirname, './imports-path/'), }, }, build: { diff --git a/playground/hmr-root/vite.config.ts b/playground/hmr-root/vite.config.ts index 8afcd8e3770834..0170945efc5ade 100644 --- a/playground/hmr-root/vite.config.ts +++ b/playground/hmr-root/vite.config.ts @@ -1,9 +1,6 @@ import path from 'node:path' -import url from 'node:url' import { defineConfig } from 'vite' -const __dirname = path.dirname(url.fileURLToPath(import.meta.url)) - export default defineConfig({ - root: path.join(__dirname, './root'), + root: path.join(import.meta.dirname, './root'), }) diff --git a/playground/hmr/vite.config.ts b/playground/hmr/vite.config.ts index 21b0b1aa296a06..0ca15749f7274a 100644 --- a/playground/hmr/vite.config.ts +++ b/playground/hmr/vite.config.ts @@ -110,7 +110,7 @@ function watchCssDepsPlugin(): Plugin { // replace the `replaced` identifier in the CSS file with the adjacent // `dep.js` file's `color` variable. if (id.includes('css-deps/main.css')) { - const depPath = path.resolve(__dirname, './css-deps/dep.js') + const depPath = path.resolve(import.meta.dirname, './css-deps/dep.js') const dep = await fs.readFile(depPath, 'utf-8') const color = dep.match(/color = '(.+?)'/)[1] this.addWatchFile(depPath) diff --git a/playground/html/vite.config.js b/playground/html/vite.config.js index 11e433128074c3..035c9cddb691f3 100644 --- a/playground/html/vite.config.js +++ b/playground/html/vite.config.js @@ -1,46 +1,48 @@ import { relative, resolve } from 'node:path' import { defineConfig } from 'vite' +const dirname = import.meta.dirname + export default defineConfig({ base: './', build: { rollupOptions: { input: { - main: resolve(__dirname, 'index.html'), - nested: resolve(__dirname, 'nested/index.html'), - scriptAsync: resolve(__dirname, 'scriptAsync.html'), - scriptMixed: resolve(__dirname, 'scriptMixed.html'), - emptyAttr: resolve(__dirname, 'emptyAttr.html'), - link: resolve(__dirname, 'link.html'), - 'link/target': resolve(__dirname, 'index.html'), - zeroJS: resolve(__dirname, 'zeroJS.html'), - noHead: resolve(__dirname, 'noHead.html'), - noBody: resolve(__dirname, 'noBody.html'), - inlinea: resolve(__dirname, 'inline/shared_a.html'), - inline1: resolve(__dirname, 'inline/shared-1.html'), - inline2: resolve(__dirname, 'inline/shared-2.html'), - inline3: resolve(__dirname, 'inline/unique.html'), + main: resolve(dirname, 'index.html'), + nested: resolve(dirname, 'nested/index.html'), + scriptAsync: resolve(dirname, 'scriptAsync.html'), + scriptMixed: resolve(dirname, 'scriptMixed.html'), + emptyAttr: resolve(dirname, 'emptyAttr.html'), + link: resolve(dirname, 'link.html'), + 'link/target': resolve(dirname, 'index.html'), + zeroJS: resolve(dirname, 'zeroJS.html'), + noHead: resolve(dirname, 'noHead.html'), + noBody: resolve(dirname, 'noBody.html'), + inlinea: resolve(dirname, 'inline/shared_a.html'), + inline1: resolve(dirname, 'inline/shared-1.html'), + inline2: resolve(dirname, 'inline/shared-2.html'), + inline3: resolve(dirname, 'inline/unique.html'), unicodePath: resolve( - __dirname, + dirname, 'unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html', ), - linkProps: resolve(__dirname, 'link-props/index.html'), - valid: resolve(__dirname, 'valid.html'), - importmapOrder: resolve(__dirname, 'importmapOrder.html'), - env: resolve(__dirname, 'env.html'), - sideEffects: resolve(__dirname, 'side-effects/index.html'), - 'a á': resolve(__dirname, 'a á.html'), - serveFile: resolve(__dirname, 'serve/file.html'), - serveFolder: resolve(__dirname, 'serve/folder/index.html'), - serveBothFile: resolve(__dirname, 'serve/both.html'), - serveBothFolder: resolve(__dirname, 'serve/both/index.html'), - write: resolve(__dirname, 'write.html'), - 'transform-inline-js': resolve(__dirname, 'transform-inline-js.html'), + linkProps: resolve(dirname, 'link-props/index.html'), + valid: resolve(dirname, 'valid.html'), + importmapOrder: resolve(dirname, 'importmapOrder.html'), + env: resolve(dirname, 'env.html'), + sideEffects: resolve(dirname, 'side-effects/index.html'), + 'a á': resolve(dirname, 'a á.html'), + serveFile: resolve(dirname, 'serve/file.html'), + serveFolder: resolve(dirname, 'serve/folder/index.html'), + serveBothFile: resolve(dirname, 'serve/both.html'), + serveBothFolder: resolve(dirname, 'serve/both/index.html'), + write: resolve(dirname, 'write.html'), + 'transform-inline-js': resolve(dirname, 'transform-inline-js.html'), relativeInput: relative( process.cwd(), - resolve(__dirname, 'relative-input.html'), + resolve(dirname, 'relative-input.html'), ), - malformedUrl: resolve(__dirname, 'malformed-url.html'), + malformedUrl: resolve(dirname, 'malformed-url.html'), }, external: ['/external-path-by-rollup-options.js'], }, diff --git a/playground/legacy/vite.config-no-polyfills-no-systemjs.js b/playground/legacy/vite.config-no-polyfills-no-systemjs.js index 388ee5a3ba71a4..33f076f2132571 100644 --- a/playground/legacy/vite.config-no-polyfills-no-systemjs.js +++ b/playground/legacy/vite.config-no-polyfills-no-systemjs.js @@ -21,7 +21,10 @@ export default defineConfig(({ isPreview }) => ({ outDir: 'dist/no-polyfills-no-systemjs', rollupOptions: { input: { - index: path.resolve(__dirname, 'no-polyfills-no-systemjs.html'), + index: path.resolve( + import.meta.dirname, + 'no-polyfills-no-systemjs.html', + ), }, }, }, diff --git a/playground/legacy/vite.config-no-polyfills.js b/playground/legacy/vite.config-no-polyfills.js index a33a34aa20e556..cbf8b3c00805b7 100644 --- a/playground/legacy/vite.config-no-polyfills.js +++ b/playground/legacy/vite.config-no-polyfills.js @@ -20,7 +20,7 @@ export default defineConfig(({ isPreview }) => ({ outDir: 'dist/no-polyfills', rollupOptions: { input: { - index: path.resolve(__dirname, 'no-polyfills.html'), + index: path.resolve(import.meta.dirname, 'no-polyfills.html'), }, }, }, diff --git a/playground/legacy/vite.config-watch.js b/playground/legacy/vite.config-watch.js index 48d57f3e988edc..1cd346adb1dff8 100644 --- a/playground/legacy/vite.config-watch.js +++ b/playground/legacy/vite.config-watch.js @@ -8,7 +8,10 @@ export default defineConfig({ manifest: true, rollupOptions: { input: { - 'style-only-entry': resolve(__dirname, 'style-only-entry.css'), + 'style-only-entry': resolve( + import.meta.dirname, + 'style-only-entry.css', + ), }, }, watch: {}, diff --git a/playground/legacy/vite.config.js b/playground/legacy/vite.config.js index d07d295a0a27d8..c822b5d60b066b 100644 --- a/playground/legacy/vite.config.js +++ b/playground/legacy/vite.config.js @@ -19,8 +19,8 @@ export default defineConfig({ assetsInlineLimit: 100, // keep SVG as assets URL rollupOptions: { input: { - index: path.resolve(__dirname, 'index.html'), - nested: path.resolve(__dirname, 'nested/index.html'), + index: path.resolve(import.meta.dirname, 'index.html'), + nested: path.resolve(import.meta.dirname, 'nested/index.html'), }, output: { chunkFileNames(chunkInfo) { @@ -40,7 +40,7 @@ export default defineConfig({ // for tests, remove `