|
2 | 2 | import type {TSModuleGraph} from './TSModuleGraph';
|
3 | 3 |
|
4 | 4 | import nullthrows from 'nullthrows';
|
5 |
| -import ts from 'typescript'; |
| 5 | +import ts, {type EntityName} from 'typescript'; |
6 | 6 | import {TSModule} from './TSModule';
|
7 | 7 | import {getExportedName, isDeclaration} from './utils';
|
8 | 8 |
|
@@ -91,16 +91,9 @@ export function collect(
|
91 | 91 | ts.isStringLiteral(node.argument.literal)
|
92 | 92 | ) {
|
93 | 93 | let local = `$$parcel$import$${moduleGraph.syntheticImportCount++}`;
|
94 |
| - if (node.qualifier) { |
95 |
| - currentModule.addImport( |
96 |
| - local, |
97 |
| - node.argument.literal.text, |
98 |
| - node.qualifier.text, |
99 |
| - ); |
100 |
| - } else { |
101 |
| - currentModule.addImport(local, node.argument.literal.text, '*'); |
102 |
| - } |
103 |
| - return factory.createTypeReferenceNode(local, node.typeArguments); |
| 94 | + let [specifier, entity] = getImportName(node.qualifier, local, factory); |
| 95 | + currentModule.addImport(local, node.argument.literal.text, specifier); |
| 96 | + return factory.createTypeReferenceNode(entity, node.typeArguments); |
104 | 97 | }
|
105 | 98 |
|
106 | 99 | // Handle `export default name;`
|
@@ -142,3 +135,23 @@ export function collect(
|
142 | 135 |
|
143 | 136 | return ts.visitNode(sourceFile, visit);
|
144 | 137 | }
|
| 138 | + |
| 139 | +// Traverse down an EntityName to the root identifier. Return that to use as the named import specifier, |
| 140 | +// and collect the remaining parts into a new QualifiedName with the local replacement at the root. |
| 141 | +// import('react').JSX.Element => import {JSX} from 'react'; JSX.Element |
| 142 | +function getImportName( |
| 143 | + qualifier: ?EntityName, |
| 144 | + local: string, |
| 145 | + factory: typeof ts, |
| 146 | +) { |
| 147 | + if (!qualifier) { |
| 148 | + return ['*', factory.createIdentifier(local)]; |
| 149 | + } |
| 150 | + |
| 151 | + if (qualifier.kind === ts.SyntaxKind.Identifier) { |
| 152 | + return [qualifier.text, factory.createIdentifier(local)]; |
| 153 | + } |
| 154 | + |
| 155 | + let [name, entity] = getImportName(qualifier.left, local, factory); |
| 156 | + return [name, factory.createQualifiedName(entity, qualifier.right)]; |
| 157 | +} |
0 commit comments