Skip to content

Commit 5812ec5

Browse files
authored
perf(mocker): find dynamic imports with es-module-lexer (#12028)
1 parent b7572c1 commit 5812ec5

2 files changed

Lines changed: 64 additions & 34 deletions

File tree

‎packages/mocker/src/node/dynamicImportPlugin.ts‎

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1+
import type { ImportSpecifier } from 'es-module-lexer'
12
import type { SourceMap } from 'magic-string'
2-
import type { Environment, Plugin, Rollup } from 'vite'
3-
import type { Expression, Positioned } from './esmWalker'
3+
import type { Environment, Plugin } from 'vite'
4+
import { initSync, parse } from 'es-module-lexer'
45
import MagicString from 'magic-string'
5-
import { esmWalker } from './esmWalker'
66

77
const regexDynamicImport = /import\s*\(/
88

@@ -28,7 +28,7 @@ export function dynamicImportPlugin(options: DynamicImportPluginOptions = {}): P
2828
if (options.filter && !options.filter(id, this.environment)) {
2929
return
3030
}
31-
return injectDynamicImport(source, id, this.parse, options)
31+
return injectDynamicImport(source, id, options)
3232
},
3333
},
3434
}
@@ -42,43 +42,35 @@ export interface DynamicImportInjectorResult {
4242
export function injectDynamicImport(
4343
code: string,
4444
id: string,
45-
parse: Rollup.PluginContext['parse'],
4645
options: DynamicImportPluginOptions = {},
4746
): DynamicImportInjectorResult | undefined {
4847
if (code.includes('wrapDynamicImport')) {
4948
return
5049
}
5150

52-
const s = new MagicString(code)
53-
54-
let ast: ReturnType<Rollup.PluginContext['parse']>
51+
initSync()
52+
let imports: readonly ImportSpecifier[]
5553
try {
56-
ast = parse(code)
54+
imports = parse(code, id)[0]
5755
} catch (err) {
5856
console.error(`Cannot parse ${id}:\n${(err as any).message}`)
5957
return
6058
}
6159

62-
// 3. convert references to import bindings & import.meta references
63-
esmWalker(ast, {
64-
// TODO: make env updatable
65-
onImportMeta() {
66-
// s.update(node.start, node.end, viImportMetaKey)
67-
},
68-
onDynamicImport(node) {
69-
const globalThisAccessor = options.globalThisAccessor || '"__vitest_mocker__"'
70-
const replaceString = `globalThis[${globalThisAccessor}].wrapDynamicImport(async () => import(`
71-
const importSubstring = code.substring(node.start, node.end)
72-
const hasIgnore = importSubstring.includes('/* @vite-ignore */')
73-
s.overwrite(
74-
node.start,
75-
(node.source as Positioned<Expression>).start,
76-
replaceString + (hasIgnore ? '/* @vite-ignore */ ' : ''),
77-
)
78-
s.overwrite(node.end - 1, node.end, '))')
79-
},
80-
})
60+
const globalThisAccessor = options.globalThisAccessor || '"__vitest_mocker__"'
61+
const s = new MagicString(code)
62+
for (const { d, ss, se } of imports) {
63+
// -1 is a static import, -2 is `import.meta`
64+
if (d < 0) {
65+
continue
66+
}
67+
s.appendLeft(ss, `globalThis[${globalThisAccessor}].wrapDynamicImport(async () => `)
68+
s.appendRight(se, ')')
69+
}
8170

71+
if (!s.hasChanged()) {
72+
return
73+
}
8274
return {
8375
code: s.toString(),
8476
map: s.generateMap({ hires: 'boundary', source: id }),

‎test/unit/test/injector-esm.test.ts‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
import { parseAst } from 'vite'
21
import { expect, test } from 'vitest'
32
import { injectDynamicImport } from '../../../packages/mocker/src/node/dynamicImportPlugin'
43

5-
function parse(code: string, options: any): any {
6-
return parseAst(code, options)
7-
}
8-
94
function injectSimpleCode(code: string) {
10-
return injectDynamicImport(code, '/test.js', parse)?.code
5+
return injectDynamicImport(code, '/test.js')?.code
116
}
127

138
test('dynamic import', async () => {
@@ -23,3 +18,46 @@ test('dynamic import with await in the argument', async () => {
2318
`"export const i = async () => globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import(await getSpecifier()))"`,
2419
)
2520
})
21+
22+
test('dynamic import keeps comments and options', async () => {
23+
const result = injectSimpleCode(
24+
"export const i = (url) => import(/* @vite-ignore */ url, { with: { type: 'json' } })",
25+
)
26+
expect(result).toMatchInlineSnapshot(
27+
`"export const i = (url) => globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import(/* @vite-ignore */ url, { with: { type: 'json' } }))"`,
28+
)
29+
})
30+
31+
test('nested dynamic import', async () => {
32+
const result = injectSimpleCode("export const i = () => import(import('./a').then((m) => m.b))")
33+
expect(result).toMatchInlineSnapshot(
34+
`"export const i = () => globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import(globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import('./a')).then((m) => m.b)))"`,
35+
)
36+
})
37+
38+
test('dynamic import in a template literal', async () => {
39+
const result = injectSimpleCode(`export const i = \`\${await import('./a')}\``)
40+
expect(result).toMatchInlineSnapshot(
41+
`"export const i = \`\${await globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import('./a'))}\`"`,
42+
)
43+
})
44+
45+
test('deferred dynamic import keeps its phase', async () => {
46+
const result = injectSimpleCode("export const i = () => import.defer('./a')")
47+
expect(result).toMatchInlineSnapshot(
48+
`"export const i = () => globalThis["__vitest_mocker__"].wrapDynamicImport(async () => import.defer('./a'))"`,
49+
)
50+
})
51+
52+
test('ignores code without a dynamic import', async () => {
53+
const result = injectSimpleCode(
54+
[
55+
"const s = 'import(x)'",
56+
'const r = /import\\(/',
57+
"obj.import('./a')",
58+
'class A { import(x) { return x } }',
59+
'console.log(import.meta.url)',
60+
].join('\n'),
61+
)
62+
expect(result).toBeUndefined()
63+
})

0 commit comments

Comments
 (0)