Skip to content

Commit

Permalink
feat: introduce fallback loaders
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Jul 29, 2024
1 parent c112de8 commit 62a49a3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
37 changes: 28 additions & 9 deletions src/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export async function importx<T = any>(_specifier: string | URL, _options: strin
excludeLoaders = [],
listDependencies = null,
ignoreImportxWarning = false,
fallbackLoaders = ['jiti'],
...otherOptions
} = options

Expand Down Expand Up @@ -89,9 +90,10 @@ export async function importx<T = any>(_specifier: string | URL, _options: strin
timestampLoad: -1,
}

debug(`[${loader}]`, 'Importing', fullPath, 'from', parentPath)
async function run(loader: SupportedLoader) {
info.loader = loader
debug(`[${loader}]`, 'Importing', fullPath, 'from', parentPath)

async function run() {
switch (loader) {
case 'native': {
if (cache === false && !ignoreImportxWarning)
Expand Down Expand Up @@ -134,13 +136,30 @@ export async function importx<T = any>(_specifier: string | URL, _options: strin
}
}

const mod = await run()
info.timestampLoad = Date.now()
const previous = _moduleInfoMap.get(mod)
if (previous)
info.previousImportInfo = previous
_moduleInfoMap.set(mod, info)
return mod
const loaders = new Set([
loader,
...fallbackLoaders || [],
])

let error: unknown | undefined

for (const loader of loaders) {
try {
const mod = await run(loader)
info.timestampLoad = Date.now()
const previous = _moduleInfoMap.get(mod)
if (previous)
info.previousImportInfo = previous
_moduleInfoMap.set(mod, info)
return mod
}
catch (err) {
error = err
debug(`[${loader}]`, err)
}
}

throw error
}

function getLoaderFromEnv(): SupportedLoader | undefined {
Expand Down
6 changes: 6 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ export interface ImportxOptions extends FeaturesOptions {
* @default 'auto'
*/
loader?: SupportedLoader | 'auto'
/**
* Fallback loaders used to import the module.
*
* @default ['jiti']
*/
fallbackLoaders?: SupportedLoader[] | false
/**
* Options for each loader
* Only the loader that is used will be applied.
Expand Down

0 comments on commit 62a49a3

Please sign in to comment.