diff --git a/packages/vite/src/node/ssr/__tests__/fixtures/modules/import-meta.js b/packages/vite/src/node/ssr/__tests__/fixtures/modules/import-meta.js new file mode 100644 index 00000000000000..cdaa5035d7ef4e --- /dev/null +++ b/packages/vite/src/node/ssr/__tests__/fixtures/modules/import-meta.js @@ -0,0 +1,2 @@ +export const dirname = import.meta.dirname +export const filename = import.meta.filename diff --git a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts b/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts index 192b0b8cd3326f..b3f3c2364ef04b 100644 --- a/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts +++ b/packages/vite/src/node/ssr/__tests__/ssrLoadModule.spec.ts @@ -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) +}) diff --git a/packages/vite/src/node/ssr/ssrModuleLoader.ts b/packages/vite/src/node/ssr/ssrModuleLoader.ts index 49428987956904..186922ff84c40b 100644 --- a/packages/vite/src/node/ssr/ssrModuleLoader.ts +++ b/packages/vite/src/node/ssr/ssrModuleLoader.ts @@ -10,6 +10,7 @@ import { genSourceMapUrl } from '../server/sourcemap' import { AsyncFunction, asyncFunctionDeclarationPaddingLineCount, + isWindows, unwrapId, } from '../../shared/utils' import { @@ -112,7 +113,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(), }