-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.ts
208 lines (169 loc) · 6.38 KB
/
index.ts
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { Plugin } from 'rollup';
import { createFilter } from 'rollup-pluginutils';
import MagicString from 'magic-string';
import { extname } from 'path';
// Parsing
import { parse, ParserPlugin } from '@babel/parser';
import traverse, { NodePath } from '@babel/traverse';
import { Node, ImportDeclaration, CallExpression, ExportNamedDeclaration, ExportAllDeclaration, StringLiteral } from '@babel/types';
enum NodeType {
Literal = 'StringLiteral',
CallExpresssion = 'CallExpression',
Identifier = 'Identifier',
ImportDeclaration = 'ImportDeclaration',
ExportNamedDeclaration = 'ExportNamedDeclaration',
ExportAllDeclaration = 'ExportAllDeclaration',
}
const defaultPlugins: ParserPlugin[] = [
'dynamicImport',
'classProperties',
'objectRestSpread',
];
export interface IRenameExtensionsOptions {
/**
* Files to include for potential renames.
* Also denotes files of which may import a renamed module in
* order to update their imports.
*/
include?: Array<string | RegExp> | string | RegExp | null;
/**
* Files to explicitly exclude
*/
exclude?: Array<string | RegExp> | string | RegExp | null;
/**
* Generate source maps for the transformations.
*/
sourceMap?: boolean;
/**
* Babel plugins to use for parsing. Defaults to:
* `dynamicImport`, `classProperties`, `objectRestSpread`
*
* For a full list visit https://babeljs.io/docs/en/babel-parser#plugins
*/
parserPlugins?: ParserPlugin[];
/**
* Object describing the transformations to use.
* IE. Input Extension => Output Extensions.
* Extensions should include the dot for both input and output.
*/
mappings: Record<string, string>;
}
function isEmpty(array: any[] | undefined) {
return !array || array.length === 0;
}
function isLiteral(node: CallExpression['arguments'][0] | undefined | null): node is StringLiteral {
return !!node && node.type === NodeType.Literal;
}
export function getRequireSource(node: CallExpression): StringLiteral | false {
if (isEmpty(node.arguments)) {
return false;
}
const args = node.arguments;
const firstArg = args[0];
if (!isLiteral(firstArg)) {
return false;
}
const isRequire = node.callee.type === 'Identifier' && node.callee.name === 'require';
if (node.callee.type === 'Import' || isRequire) {
return firstArg;
}
return firstArg;
}
function getImportSource(node: ImportDeclaration): StringLiteral | false {
if (node.type === NodeType.ImportDeclaration) {
return node.source;
}
return false;
}
function getExportSource(node: ExportAllDeclaration | ExportNamedDeclaration): StringLiteral | false {
if (!node.source || node.source.type !== NodeType.Literal) {
return false;
}
return node.source;
}
function rewrite(
input: string,
extensions: Record<string, string>,
): string | false {
const extension = extname(input);
if (extensions.hasOwnProperty(extension)) {
return `${input.slice(0, -extension.length)}${extensions[extension]}`;
}
return false;
}
export default function renameExtensions(
options: IRenameExtensionsOptions,
): Plugin {
const filter = createFilter(options.include, options.exclude);
const sourceMaps = options.sourceMap !== false;
return {
name: 'rename-rollup',
generateBundle(_, bundle) {
const files = Object.entries<any>(bundle);
for (const [key, file] of files) {
if (!filter(file.facadeModuleId)) {
continue;
}
file.facadeModuleId =
rewrite(file.facadeModuleId, options.mappings) ||
file.facadeModuleId;
file.fileName =
rewrite(file.fileName, options.mappings) || file.fileName;
file.imports.map((imported: string) => {
if (!filter(imported)) {
return imported;
}
return rewrite(imported, options.mappings) || imported;
});
if (file.code) {
const magicString = new MagicString(file.code);
const ast = parse(file.code, {
sourceType: 'module',
plugins: options.parserPlugins || defaultPlugins,
});
const extract = (path: NodePath<Node>) => {
let req: StringLiteral | false = false;
if (path.isImportDeclaration()) {
req = getImportSource(path.node);
}
if (path.isCallExpression()) {
req = getRequireSource(path.node);
}
if (path.isExportAllDeclaration() || path.isExportNamedDeclaration()) {
req = getExportSource(path.node);
}
if (req) {
const { start, end } = req;
if (!start || !end) {
throw new Error('Error occurred when trying to get the start and end positions of imports.');
}
const newPath = rewrite(
req.value,
options.mappings,
);
if (newPath) {
magicString.overwrite(
start,
end,
`'${newPath}'`,
);
}
}
};
traverse(ast, {
ImportDeclaration: extract,
CallExpression: extract,
ExportAllDeclaration: extract,
ExportNamedDeclaration: extract,
});
if (sourceMaps) {
file.map = magicString.generateMap();
}
file.code = magicString.toString();
}
delete bundle[key];
bundle[rewrite(key, options.mappings) || key] = file;
}
},
};
}