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(ssr): import.meta.filename/dirname support #15887

Merged
merged 3 commits into from
Mar 12, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const dirname = import.meta.dirname
export const filename = import.meta.filename
10 changes: 10 additions & 0 deletions packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,13 @@ test('error has same instance', async () => {
expect(e[s]).toBe(true)
}
})

test('import.meta.filename/dirname returns same value with Node', async () => {
const server = await createDevServer()
const moduleRelativePath = '/fixtures/modules/import-meta.js'
const filename = path.resolve(root, '.' + moduleRelativePath)

const viteValue = await server.ssrLoadModule(moduleRelativePath)
expect(viteValue.dirname).toBe(path.dirname(filename))
expect(viteValue.filename).toBe(filename)
})
13 changes: 12 additions & 1 deletion packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import path from 'node:path'
import { pathToFileURL } from 'node:url'
import colors from 'picocolors'
import type { ViteDevServer } from '../server'
import { isBuiltin, isExternalUrl, isFilePathESM, unwrapId } from '../utils'
import {
isBuiltin,
isExternalUrl,
isFilePathESM,
isWindows,
unwrapId,
} from '../utils'
import { transformRequest } from '../server/transformRequest'
import type { InternalResolveOptionsWithOverrideConditions } from '../plugins/resolve'
import { tryNodeResolve } from '../plugins/resolve'
Expand Down Expand Up @@ -127,7 +133,12 @@ async function instantiateModule(
// referenced before it's been instantiated.
mod.ssrModule = ssrModule

// replace '/' with '\\' on Windows to match Node.js
const osNormalizedFilename = isWindows ? path.resolve(mod.file!) : mod.file!

const ssrImportMeta = {
dirname: path.dirname(osNormalizedFilename),
filename: osNormalizedFilename,
// The filesystem URL, matching native Node.js modules
url: pathToFileURL(mod.file!).toString(),
}
Expand Down