fix: support multiline dynamic imports (#9314)

This commit is contained in:
Bjorn Lu 2022-07-23 15:09:45 +08:00 committed by GitHub
parent b82ee5d39b
commit e66cf69cc2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 5 deletions

View File

@ -10,6 +10,7 @@ import {
createFilter,
normalizePath,
parseRequest,
removeComments,
requestQuerySplitRE,
transformStableResult
} from '../utils'
@ -176,11 +177,13 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
s ||= new MagicString(source)
let result
try {
result = await transformDynamicImport(
source.slice(start, end),
importer,
resolve
)
// When import string is using backticks, es-module-lexer `end` captures
// until the closing parenthesis, instead of the closing backtick.
// There may be inline comments between the backtick and the closing
// 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)
} catch (error) {
if (warnOnError) {
this.warn(error)

View File

@ -984,6 +984,10 @@ export function emptyCssComments(raw: string): string {
return raw.replace(multilineCommentsRE, (s) => ' '.repeat(s.length))
}
export function removeComments(raw: string): string {
return raw.replace(multilineCommentsRE, '').replace(singlelineCommentsRE, '')
}
function mergeConfigRecursively(
defaults: Record<string, any>,
overrides: Record<string, any>,

View File

@ -68,6 +68,14 @@ test('should load dynamic import with vars', async () => {
)
})
test('should load dynamic import with vars multiline', async () => {
await untilUpdated(
() => page.textContent('.dynamic-import-with-vars'),
'hello',
true
)
})
test('should load dynamic import with vars alias', async () => {
await untilUpdated(
() => page.textContent('.dynamic-import-with-vars-alias'),

View File

@ -84,6 +84,15 @@ import(`../alias/${base}.js`).then((mod) => {
text('.dynamic-import-with-vars', mod.hello())
})
// prettier-ignore
import(
/* this messes with */
`../alias/${base}.js`
/* es-module-lexer */
).then((mod) => {
text('.dynamic-import-with-vars-multiline', mod.hello())
})
import(`../alias/${base}.js?raw`).then((mod) => {
text('.dynamic-import-with-vars-raw', JSON.stringify(mod))
})