@@ -5,7 +5,7 @@ import { blue, underline, yellow } from 'ansis'
55import { createDebug } from 'obug'
66import { RE_DTS , RE_NODE_MODULES } from 'rolldown-plugin-dts/internal'
77import { and , id , importerId , include } from 'rolldown/filter'
8- import { parse } from 'rolldown/utils'
8+ import { parse , Visitor , type ESTree } from 'rolldown/utils'
99import {
1010 matchPattern ,
1111 resolveRegex ,
@@ -56,7 +56,8 @@ export interface DepsConfig {
5656 * Node built-in modules are always allowed to be imported
5757 * when `platform` is `node`.
5858 *
59- * Note: Only ESM output is checked. CJS output (`require` calls) is not detected.
59+ * Note: ES imports and dynamic import expressions are checked. CJS
60+ * `require` calls are not detected.
6061 */
6162 onlyImport ?: Arrayable < string | RegExp >
6263 /**
@@ -273,18 +274,9 @@ export function DepsPlugin(
273274 moduleIds . some ( ( id ) => chunk . code . includes ( id ) )
274275 ) {
275276 const { program } = await parse ( chunk . fileName , chunk . code )
276- for ( const stmt of program . body ) {
277- if (
278- stmt . type !== 'ImportDeclaration' &&
279- stmt . type !== 'ExportAllDeclaration' &&
280- stmt . type !== 'ExportNamedDeclaration'
281- ) {
282- continue
283- }
284- const source = stmt . source ?. value
285-
277+ for ( const source of collectImportSources ( program ) ) {
286278 // relative imports of sibling chunks emitted by code splitting
287- if ( ! source || source [ 0 ] === '.' ) continue
279+ if ( source [ 0 ] === '.' ) continue
288280 if ( platform === 'node' && isBuiltin ( source ) ) continue
289281 if ( matchPattern ( parsePackageSpecifier ( source ) [ 0 ] , onlyImport ) ) {
290282 continue
@@ -421,6 +413,40 @@ export function DepsPlugin(
421413 }
422414}
423415
416+ function collectImportSources ( program : ESTree . Program ) : string [ ] {
417+ const sources : string [ ] = [ ]
418+
419+ new Visitor ( {
420+ ImportDeclaration ( node ) {
421+ sources . push ( node . source . value )
422+ } ,
423+ ExportAllDeclaration ( node ) {
424+ sources . push ( node . source . value )
425+ } ,
426+ ExportNamedDeclaration ( node ) {
427+ if ( node . source ) sources . push ( node . source . value )
428+ } ,
429+ ImportExpression ( node ) {
430+ const source = getStaticString ( node . source )
431+ if ( source ) sources . push ( source )
432+ } ,
433+ } ) . visit ( program )
434+
435+ return sources
436+ }
437+
438+ function getStaticString ( value : ESTree . Expression ) : string | undefined {
439+ if ( value . type === 'Literal' && typeof value . value === 'string' ) {
440+ return value . value
441+ }
442+
443+ if ( value . type !== 'TemplateLiteral' ) return
444+ if ( value . expressions . length || value . quasis . length !== 1 ) return
445+
446+ const { cooked, raw } = value . quasis [ 0 ] . value
447+ return cooked ?? raw
448+ }
449+
424450export function parsePackageSpecifier (
425451 id : string ,
426452) : [ name : string , subpath : string ] {
0 commit comments