This repository has been archived by the owner on Mar 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 363
/
stub.ts
69 lines (61 loc) · 2.03 KB
/
stub.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
import MagicString from 'magic-string';
import { Plugin } from 'rollup';
import winPath from '../../winPath';
interface Options {
modules?: string[];
sourceMap?: boolean;
}
export default function stub(options: Options = {}): Plugin {
return {
name: 'stub',
transform(code: string, id: string) {
if (options.modules) {
if (
options.modules.every(
module => winPath(id).indexOf(winPath(module)) === -1
)
) {
return null;
}
}
let ast = this.parse(code, {
sourceType: 'module',
});
const exports: string[] = [];
ast.body.forEach((node: any) => {
if (node.type === 'ExportDefaultDeclaration') {
exports.push(`\nexport default function() {};`);
} else if (node.type === 'ExportNamedDeclaration') {
if (node.declaration == null) {
let content = '';
node.specifiers.forEach((specifier: any) => {
content += `\nexport var ${specifier.exported.name} = function() {};`;
});
exports.push(content);
} else if (node.declaration.type === 'VariableDeclaration') {
node.declaration.declarations.forEach((declaration: any) => {
exports.push(
`\nexport var ${declaration.id.name} = function() {};`
);
});
} else if (node.declaration.type === 'FunctionDeclaration') {
exports.push(
`\nexport var ${node.declaration.id.name} = function() {};`
);
} else if (node.declaration.type === 'ClassDeclaration') {
exports.push(
`\nexport var ${node.declaration.id.name} = function() {};`
);
}
}
});
const magicString = new MagicString(exports.join(''));
code = magicString.toString();
const map = options.sourceMap ? magicString.generateMap() : null;
ast = this.parse(code, {
sourceType: 'module',
});
return { code, map };
},
};
}