Skip to content

Commit

Permalink
refactor: move logic to transformDynamicImport
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Jul 28, 2022
1 parent 840560d commit 8432015
Showing 1 changed file with 19 additions and 15 deletions.
34 changes: 19 additions & 15 deletions packages/vite/src/node/plugins/dynamicImportVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ export async function transformDynamicImport(
resolve: (
url: string,
importer?: string
) => Promise<string | undefined> | string | undefined
) => Promise<string | undefined> | string | undefined,
root: string
): Promise<{
glob: string
pattern: string
Expand Down Expand Up @@ -107,10 +108,19 @@ export async function transformDynamicImport(
? `, ${JSON.stringify({ ...globParams, import: '*' })}`
: ''

let newRawPattern = posix.relative(
posix.dirname(importer),
await toAbsoluteGlob(rawPattern, root, importer, resolve)
)

if (!/^\.{1,2}\//.test(newRawPattern)) {
newRawPattern = `./${newRawPattern}`
}

const exp = `(import.meta.glob(${JSON.stringify(userPattern)}${params}))`

return {
rawPattern,
rawPattern: newRawPattern,
pattern: userPattern,
glob: exp
}
Expand Down Expand Up @@ -185,7 +195,12 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
// parenthesis, so we manually remove them for now.
// See https://github.com/guybedford/es-module-lexer/issues/118
const importSource = removeComments(source.slice(start, end)).trim()
result = await transformDynamicImport(importSource, importer, resolve)
result = await transformDynamicImport(
importSource,
importer,
resolve,
config.root
)
} catch (error) {
if (warnOnError) {
this.warn(error)
Expand All @@ -200,22 +215,11 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {

const { rawPattern, glob } = result

let newPattern = posix.relative(
posix.dirname(importer),
await toAbsoluteGlob(rawPattern, config.root, importer, (im) =>
this.resolve(im, importer).then((i) => i?.id || im)
)
)

if (!/^\.{1,2}\//.test(newPattern)) {
newPattern = `./${newPattern}`
}

needDynamicImportHelper = true
s.overwrite(
expStart,
expEnd,
`__variableDynamicImportRuntimeHelper(${glob}, \`${newPattern}\`)`
`__variableDynamicImportRuntimeHelper(${glob}, \`${rawPattern}\`)`
)
}

Expand Down

0 comments on commit 8432015

Please sign in to comment.