1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 | import dynamicImportSyntax from '@babel/plugin-syntax-dynamic-import';
|
16 | import {NodePath} from '@babel/traverse';
|
17 | import {CallExpression, ExportAllDeclaration, ExportNamedDeclaration, ImportDeclaration, Program} from 'babel-types';
|
18 | import {resolve} from 'polymer-analyzer/lib/javascript/resolve-specifier-node';
|
19 |
|
20 | const isPathSpecifier = (s: string) => /^\.{0,2}\
|
21 |
|
22 | type HasSpecifier =
|
23 | ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration;
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | export const resolveBareSpecifiers = (
|
29 | filePath: string,
|
30 | isComponentRequest: boolean,
|
31 | packageName?: string,
|
32 | componentDir?: string,
|
33 | rootDir?: string,
|
34 | ) => ({
|
35 | inherits: dynamicImportSyntax,
|
36 |
|
37 | visitor: {
|
38 | Program(path: NodePath<Program>) {
|
39 | path.traverse({
|
40 | CallExpression(path: NodePath<CallExpression>) {
|
41 | if (path.node.callee.type as string === 'Import') {
|
42 | const specifierArg = path.node.arguments[0];
|
43 | if (specifierArg.type !== 'StringLiteral') {
|
44 |
|
45 | return;
|
46 | }
|
47 | const specifier = specifierArg.value;
|
48 | specifierArg.value = maybeResolve(
|
49 | specifier,
|
50 | filePath,
|
51 | isComponentRequest,
|
52 | packageName,
|
53 | componentDir,
|
54 | rootDir);
|
55 | }
|
56 | }
|
57 | });
|
58 | },
|
59 | 'ImportDeclaration|ExportNamedDeclaration|ExportAllDeclaration'(
|
60 | path: NodePath<HasSpecifier>) {
|
61 | const node = path.node;
|
62 |
|
63 |
|
64 | if (node.source == null) {
|
65 | return;
|
66 | }
|
67 |
|
68 | const specifier = node.source.value;
|
69 | node.source.value = maybeResolve(
|
70 | specifier,
|
71 | filePath,
|
72 | isComponentRequest,
|
73 | packageName,
|
74 | componentDir,
|
75 | rootDir);
|
76 | }
|
77 | }
|
78 | });
|
79 |
|
80 | const maybeResolve = (
|
81 | specifier: string,
|
82 | filePath: string,
|
83 | isComponentRequest: boolean,
|
84 | packageName?: string,
|
85 | componentDir?: string,
|
86 | rootDir?: string,
|
87 | ) => {
|
88 | try {
|
89 | let componentInfo;
|
90 | if (isComponentRequest) {
|
91 | componentInfo = {
|
92 | packageName: packageName!,
|
93 | componentDir: componentDir!,
|
94 | rootDir: rootDir!,
|
95 | };
|
96 | }
|
97 | return resolve(specifier, filePath, componentInfo);
|
98 | } catch (e) {
|
99 |
|
100 |
|
101 | if (!isPathSpecifier(specifier) && specifier !== 'require' &&
|
102 | specifier !== 'meta') {
|
103 |
|
104 |
|
105 |
|
106 | console.warn(
|
107 | `Could not resolve module specifier "${specifier}" ` +
|
108 | `in file "${filePath}".`);
|
109 | }
|
110 | return specifier;
|
111 | }
|
112 | };
|