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
13 changes: 13 additions & 0 deletions packages/vite/src/module-runner/importMetaResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,16 @@ export async function createImportMetaResolver(): Promise<
`${customizationHookNamespace}${JSON.stringify([specifier, importer])}`,
)
}

// NOTE: use computed string to avoid `define` replacing `import.meta.resolve` when bundled
export const importMetaResolveWithCustomHookString: string = /* js */ `

(() => {
const resolve = 'resolve'
return (specifier, importer) =>
import.meta[resolve](
\`${customizationHookNamespace}\${JSON.stringify([specifier, importer])}\`,
)
})()

Comment thread
sapphi-red marked this conversation as resolved.
`
3 changes: 2 additions & 1 deletion packages/vite/src/node/__tests__/config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,7 @@ describe('loadConfigFromFile', () => {
`)
})

test('import.meta.main is correctly set', async () => {
test('import.meta properties are supported', async () => {
const { config } = (await loadConfigFromFile(
{} as any,
path.resolve(fixtures, './import-meta/vite.config.ts'),
Expand All @@ -851,6 +851,7 @@ describe('loadConfigFromFile', () => {
expect(c.url).toContain('file://')
expect(c.dirname).toContain('import-meta')
expect(c.filename).toContain('vite.config.ts')
expect(c.resolved).toBe(c.url)
})

describe('loadConfigFromFile with configLoader: native', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"type": "module"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ export default {
url: import.meta.url,
dirname: import.meta.dirname,
filename: import.meta.filename,
resolved: import.meta.resolve('../import-meta/vite.config.ts'),
}
22 changes: 21 additions & 1 deletion packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ import { build } from 'esbuild'
import type { Alias, AliasOptions } from '#dep-types/alias'
import type { AnymatchFn } from '../types/anymatch'
import { withTrailingSlash } from '../shared/utils'
import {
createImportMetaResolver,
importMetaResolveWithCustomHookString,
} from '../module-runner/importMetaResolver'
import {
CLIENT_ENTRY,
DEFAULT_ASSETS_RE,
Expand Down Expand Up @@ -1925,10 +1929,14 @@ async function bundleConfigFile(
fileName: string,
isESM: boolean,
): Promise<{ code: string; dependencies: string[] }> {
let importMetaResolverRegistered = false

const root = path.dirname(fileName)
const dirnameVarName = '__vite_injected_original_dirname'
const filenameVarName = '__vite_injected_original_filename'
const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
const importMetaResolveVarName =
'__vite_injected_original_import_meta_resolve'

const result = await build({
absWorkingDir: process.cwd(),
Expand All @@ -1949,6 +1957,7 @@ async function bundleConfigFile(
'import.meta.url': importMetaUrlVarName,
'import.meta.dirname': dirnameVarName,
'import.meta.filename': filenameVarName,
'import.meta.resolve': importMetaResolveVarName,
'import.meta.main': 'false',
},
plugins: [
Expand Down Expand Up @@ -2015,14 +2024,25 @@ async function bundleConfigFile(
setup(build) {
build.onLoad({ filter: /\.[cm]?[jt]s$/ }, async (args) => {
const contents = await fsp.readFile(args.path, 'utf-8')
const injectValues =
let injectValues =
`const ${dirnameVarName} = ${JSON.stringify(
path.dirname(args.path),
)};` +
`const ${filenameVarName} = ${JSON.stringify(args.path)};` +
`const ${importMetaUrlVarName} = ${JSON.stringify(
pathToFileURL(args.path).href,
)};`
if (contents.includes('import.meta.resolve')) {
if (isESM) {
if (!importMetaResolverRegistered) {
importMetaResolverRegistered = true
await createImportMetaResolver()
}
injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => (${importMetaResolveWithCustomHookString})(specifier, importer);`
Comment thread
sapphi-red marked this conversation as resolved.
Comment thread
sapphi-red marked this conversation as resolved.
} else {
injectValues += `const ${importMetaResolveVarName} = (specifier, importer = ${importMetaUrlVarName}) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`
}
}

return {
loader: args.path.endsWith('ts') ? 'ts' : 'js',
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.