@@ -13,6 +13,10 @@ import { build } from 'esbuild'
1313import type { Alias , AliasOptions } from '#dep-types/alias'
1414import type { AnymatchFn } from '../types/anymatch'
1515import { withTrailingSlash } from '../shared/utils'
16+ import {
17+ createImportMetaResolver ,
18+ importMetaResolveWithCustomHookString ,
19+ } from '../module-runner/importMetaResolver'
1620import {
1721 CLIENT_ENTRY ,
1822 DEFAULT_ASSETS_RE ,
@@ -1925,10 +1929,14 @@ async function bundleConfigFile(
19251929 fileName : string ,
19261930 isESM : boolean ,
19271931) : Promise < { code : string ; dependencies : string [ ] } > {
1932+ let importMetaResolverRegistered = false
1933+
19281934 const root = path . dirname ( fileName )
19291935 const dirnameVarName = '__vite_injected_original_dirname'
19301936 const filenameVarName = '__vite_injected_original_filename'
19311937 const importMetaUrlVarName = '__vite_injected_original_import_meta_url'
1938+ const importMetaResolveVarName =
1939+ '__vite_injected_original_import_meta_resolve'
19321940
19331941 const result = await build ( {
19341942 absWorkingDir : process . cwd ( ) ,
@@ -1949,6 +1957,7 @@ async function bundleConfigFile(
19491957 'import.meta.url' : importMetaUrlVarName ,
19501958 'import.meta.dirname' : dirnameVarName ,
19511959 'import.meta.filename' : filenameVarName ,
1960+ 'import.meta.resolve' : importMetaResolveVarName ,
19521961 'import.meta.main' : 'false' ,
19531962 } ,
19541963 plugins : [
@@ -2015,14 +2024,25 @@ async function bundleConfigFile(
20152024 setup ( build ) {
20162025 build . onLoad ( { filter : / \. [ c m ] ? [ j t ] s $ / } , async ( args ) => {
20172026 const contents = await fsp . readFile ( args . path , 'utf-8' )
2018- const injectValues =
2027+ let injectValues =
20192028 `const ${ dirnameVarName } = ${ JSON . stringify (
20202029 path . dirname ( args . path ) ,
20212030 ) } ;` +
20222031 `const ${ filenameVarName } = ${ JSON . stringify ( args . path ) } ;` +
20232032 `const ${ importMetaUrlVarName } = ${ JSON . stringify (
20242033 pathToFileURL ( args . path ) . href ,
20252034 ) } ;`
2035+ if ( contents . includes ( 'import.meta.resolve' ) ) {
2036+ if ( isESM ) {
2037+ if ( ! importMetaResolverRegistered ) {
2038+ importMetaResolverRegistered = true
2039+ await createImportMetaResolver ( )
2040+ }
2041+ injectValues += `const ${ importMetaResolveVarName } = (specifier, importer = ${ importMetaUrlVarName } ) => (${ importMetaResolveWithCustomHookString } )(specifier, importer);`
2042+ } else {
2043+ injectValues += `const ${ importMetaResolveVarName } = (specifier, importer = ${ importMetaUrlVarName } ) => { throw new Error('import.meta.resolve is not supported in CJS config files') };`
2044+ }
2045+ }
20262046
20272047 return {
20282048 loader : args . path . endsWith ( 'ts' ) ? 'ts' : 'js' ,
0 commit comments