-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
172 lines (153 loc) · 4.94 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const glob = require('glob');
const isGlob = require('is-glob');
const Path = require('path');
const fs = require('fs');
const identifierfy = require('identifierfy');
/* Checks the type of the import specifiers. Throws an error if any specifier isn't a default specifier. */
function assertImportDefaultSpecifier(path, specifiers) {
let hasError = specifiers.length === 0 || specifiers.length > 1
if (!hasError) {
for (const { type } of specifiers) {
if (type !== 'ImportDefaultSpecifier') {
hasError = true
break
}
}
}
if (hasError) {
throw path.buildCodeFrameError('Can only import the default export from a glob pattern');
}
}
/* Read a sibling package.json file and return the name property from it. */
function readPackageName(index) {
let pkgPath = Path.join(Path.dirname(index), "package.json")
if (!fs.existsSync(pkgPath)) {
return
}
let pkg = fs.readFileSync(pkgPath, 'utf8');
return JSON.parse(pkg).name;
}
// From novemberborn/babel-plugin-import-glob
function memberify(subpath) {
const pieces = subpath.split(Path.sep)
const prefixReservedWords = pieces.length === 1
const ids = []
for (let index = 0; index < pieces.length; index++) {
const name = pieces[index]
const id = identifierfy(name, {
prefixReservedWords,
prefixInvalidIdentifiers: index === 0
})
if (id === null) {
return null
}
ids.push(id)
}
return ids.join('$')
}
function generateNameForImport(file, baseDir) {
const name = memberify(Path.basename(Path.dirname(file)))
let pakage = readPackageName(Path.resolve(baseDir, file));
if (!pakage) {
pakage = name
}
return {
name, pakage
}
}
module.exports = function importGlobMetaPlugin(babel) {
const { types: t } = babel;
return {
visitor: {
ImportDeclaration(path, state) {
const { node: { specifiers, source } } = path
const importPath = source.value
const currentFilePath = state.file.opts.filename
const baseDir = Path.resolve(Path.dirname(currentFilePath))
// If this is not a local import, don't do anything
if (importPath[0] !== '.' && importPath[0] !== '/') return
// If the import specifier doesn't contain a glob pattern, don't do anything
if (!isGlob(importPath)) return
assertImportDefaultSpecifier(path, specifiers)
// Find file matches based on the glob pattern
let files = glob.sync(
Path.join(baseDir, importPath),
{
cwd: baseDir,
nodir: true,
strict: true
}
)
// Return let modules = [] on no matches
if (!files) {
path.replaceWith(
t.variableDeclaration("let", [
t.variableDeclarator(
t.identifier(specifiers[0].local.name), t.arrayExpression([])
)
])
)
return
}
// Compute relative paths
files = files.map(file => {
rel = Path.relative(baseDir, file)
if (rel.charAt(0) != ".") {
rel = `./${rel}`
}
return rel
})
let dict = []
files.map(file => {
const { name, pakage } = generateNameForImport(file, baseDir)
// Generate an unique placeholder for the import specifier name
const placeholder = path.scope.generateUid('_ig')
dict.push({
name, file, placeholder, pakage
})
})
let importRemappings = [], assignRemappings = [];
dict.map(item => {
// Add import with placeholder name for specifier and relative path as source
importRemappings.push(
t.importDeclaration(
[
t.importDefaultSpecifier(t.identifier(item.placeholder))
],
t.stringLiteral(item.file)
)
)
// Add an object with name, value, path and package of the imported object
assignRemappings.push(
t.objectExpression(
[
t.objectProperty(
t.stringLiteral("name"), t.stringLiteral(item.name)
),
t.objectProperty(
t.stringLiteral("value"), t.identifier(item.placeholder)
),
t.objectProperty(
t.stringLiteral("path"), t.stringLiteral(item.file)
),
t.objectProperty(
t.stringLiteral("package"), t.stringLiteral(item.pakage)
),
]
)
)
});
let assignMap = t.variableDeclaration("let", [
t.variableDeclarator(t.identifier(specifiers[0].local.name), t.arrayExpression(
assignRemappings
))
])
// Replace the path with the new imports and variable assignment
path.replaceWithMultiple([
...importRemappings,
assignMap
])
}
}
};
};