Skip to content

Commit

Permalink
feat(ssr): import.meta.filename/dirname support (#15887)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Mar 12, 2024
1 parent 8e54af6 commit 74dc73a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
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)
})
6 changes: 6 additions & 0 deletions packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { genSourceMapUrl } from '../server/sourcemap'
import {
AsyncFunction,
asyncFunctionDeclarationPaddingLineCount,
isWindows,
unwrapId,
} from '../../shared/utils'
import {
Expand Down Expand Up @@ -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(),
}
Expand Down

0 comments on commit 74dc73a

Please sign in to comment.