Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
),
]
Expand Down
5 changes: 1 addition & 4 deletions docs/guide/api-environment-frameworks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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,
Expand Down
10 changes: 2 additions & 8 deletions docs/guide/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,12 @@ async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>
**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,
},
Expand Down Expand Up @@ -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: {
Expand Down
21 changes: 6 additions & 15 deletions docs/guide/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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',
Expand All @@ -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',
},
Expand Down
6 changes: 1 addition & 5 deletions docs/guide/ssr.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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
Expand All @@ -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',
)

Expand Down
34 changes: 20 additions & 14 deletions packages/create-vite/__tests__/cli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(' ')}`, {
Expand Down Expand Up @@ -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.`,
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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'),
Expand Down Expand Up @@ -183,7 +189,7 @@ test('works with the -t alias', () => {
'--no-rolldown',
],
{
cwd: __dirname,
cwd: import.meta.dirname,
},
)
const generatedFiles = fs.readdirSync(genPath).sort()
Expand All @@ -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')
Expand All @@ -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}`)
Expand All @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-legacy/src/__tests__/readme.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
24 changes: 12 additions & 12 deletions packages/vite/rolldown.config.ts
Original file line number Diff line number Diff line change
@@ -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',
},
})
Expand Down Expand Up @@ -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\//,
Expand Down Expand Up @@ -124,7 +124,7 @@ const nodeConfig = defineConfig({
}),
buildTimeImportMetaUrlPlugin(),
licensePlugin(
path.resolve(__dirname, 'LICENSE.md'),
path.resolve(dirname, 'LICENSE.md'),
'Vite core license',
'Vite',
),
Expand All @@ -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',
Expand Down Expand Up @@ -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

Expand Down
Loading