1 | 'use strict';
|
2 |
|
3 | const { extname } = require('path');
|
4 |
|
5 | function namedAssetImportPlugin({ types: t }) {
|
6 | const visited = new WeakSet();
|
7 |
|
8 | function generateNewSourcePath(loaderMap, moduleName, sourcePath) {
|
9 | const ext = extname(sourcePath).substr(1);
|
10 | const extMap = loaderMap[ext];
|
11 | return extMap[moduleName]
|
12 | ? extMap[moduleName].replace(/\[path\]/, sourcePath)
|
13 | : sourcePath;
|
14 | }
|
15 |
|
16 | function replaceMatchingSpecifiers(path, loaderMap, callback) {
|
17 | const sourcePath = path.node.source.value;
|
18 | const ext = extname(sourcePath).substr(1);
|
19 |
|
20 | if (visited.has(path.node) || sourcePath.indexOf('!') !== -1) {
|
21 | return;
|
22 | }
|
23 |
|
24 | if (loaderMap[ext]) {
|
25 | path.replaceWithMultiple(
|
26 | path.node.specifiers.map(specifier => {
|
27 | const newSpecifier = callback(specifier, sourcePath);
|
28 | visited.add(newSpecifier);
|
29 |
|
30 | return newSpecifier;
|
31 | })
|
32 | );
|
33 | }
|
34 | }
|
35 |
|
36 | return {
|
37 | visitor: {
|
38 | ExportNamedDeclaration(path, { opts: { loaderMap } }) {
|
39 | if (!path.node.source) {
|
40 | return;
|
41 | }
|
42 |
|
43 | replaceMatchingSpecifiers(path, loaderMap, (specifier, sourcePath) => {
|
44 | if (t.isExportDefaultSpecifier(specifier)) {
|
45 | return t.exportDeclaration(
|
46 | [t.exportDefaultSpecifier(t.identifier(specifier.local.name))],
|
47 | t.stringLiteral(sourcePath)
|
48 | );
|
49 | }
|
50 |
|
51 | return t.exportNamedDeclaration(
|
52 | null,
|
53 | [
|
54 | t.exportSpecifier(
|
55 | t.identifier(specifier.local.name),
|
56 | t.identifier(specifier.exported.name)
|
57 | ),
|
58 | ],
|
59 | t.stringLiteral(
|
60 | generateNewSourcePath(loaderMap, specifier.local.name, sourcePath)
|
61 | )
|
62 | );
|
63 | });
|
64 | },
|
65 | ImportDeclaration(path, { opts: { loaderMap } }) {
|
66 | replaceMatchingSpecifiers(path, loaderMap, (specifier, sourcePath) => {
|
67 | if (t.isImportDefaultSpecifier(specifier)) {
|
68 | return t.importDeclaration(
|
69 | [t.importDefaultSpecifier(t.identifier(specifier.local.name))],
|
70 | t.stringLiteral(sourcePath)
|
71 | );
|
72 | }
|
73 |
|
74 | return t.importDeclaration(
|
75 | [
|
76 | t.importSpecifier(
|
77 | t.identifier(specifier.local.name),
|
78 | t.identifier(specifier.imported.name)
|
79 | ),
|
80 | ],
|
81 | t.stringLiteral(
|
82 | generateNewSourcePath(
|
83 | loaderMap,
|
84 | specifier.imported.name,
|
85 | sourcePath
|
86 | )
|
87 | )
|
88 | );
|
89 | });
|
90 | },
|
91 | },
|
92 | };
|
93 | }
|
94 |
|
95 | module.exports = namedAssetImportPlugin;
|