Skip to content

Commit 74dc73a

Browse files
authored
feat(ssr): import.meta.filename/dirname support (#15887)
1 parent 8e54af6 commit 74dc73a

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const dirname = import.meta.dirname
2+
export const filename = import.meta.filename

packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,13 @@ test('error has same instance', async () => {
5252
expect(e[s]).toBe(true)
5353
}
5454
})
55+
56+
test('import.meta.filename/dirname returns same value with Node', async () => {
57+
const server = await createDevServer()
58+
const moduleRelativePath = '/fixtures/modules/import-meta.js'
59+
const filename = path.resolve(root, '.' + moduleRelativePath)
60+
61+
const viteValue = await server.ssrLoadModule(moduleRelativePath)
62+
expect(viteValue.dirname).toBe(path.dirname(filename))
63+
expect(viteValue.filename).toBe(filename)
64+
})

packages/vite/src/node/ssr/ssrModuleLoader.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { genSourceMapUrl } from '../server/sourcemap'
1010
import {
1111
AsyncFunction,
1212
asyncFunctionDeclarationPaddingLineCount,
13+
isWindows,
1314
unwrapId,
1415
} from '../../shared/utils'
1516
import {
@@ -112,7 +113,12 @@ async function instantiateModule(
112113
// referenced before it's been instantiated.
113114
mod.ssrModule = ssrModule
114115

116+
// replace '/' with '\\' on Windows to match Node.js
117+
const osNormalizedFilename = isWindows ? path.resolve(mod.file!) : mod.file!
118+
115119
const ssrImportMeta = {
120+
dirname: path.dirname(osNormalizedFilename),
121+
filename: osNormalizedFilename,
116122
// The filesystem URL, matching native Node.js modules
117123
url: pathToFileURL(mod.file!).toString(),
118124
}

0 commit comments

Comments
 (0)