forked from ionic-team/ionic-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreeshaking.js
94 lines (77 loc) · 2.05 KB
/
treeshaking.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
const path = require('path');
const { rollup } = require('rollup');
const virtual = require('@rollup/plugin-virtual');
const fs = require('fs');
async function main() {
const input = process.argv[2] || getMainEntry();
const result = await check(input);
const relative = path.relative(process.cwd(), input);
if (result.shaken) {
console.error(`Success! ${relative} is fully tree-shakeable`);
} else {
error(`Failed to tree-shake ${relative}`);
};
}
function error(msg) {
console.error(msg);
process.exit(1);
}
function getMainEntry() {
if (!fs.existsSync('package.json')) {
error(`Could not find package.json`);
}
const pkg = JSON.parse(fs.readFileSync('package.json'), 'utf-8');
const unresolved = pkg.module || pkg.main || 'index';
const resolved = resolve(unresolved);
if (!resolved) {
error(`Could not resolve entry point`);
}
return resolved;
}
function resolve(file) {
if (isDirectory(file)) {
return ifExists(`${file}/index.cjs.js`) || ifExists(`${file}/index.js`);
}
return ifExists(file) || ifExists(`${file}.cjs.js`) || ifExists(`${file}.js`);
}
function isDirectory(file) {
try {
const stats = fs.statSync(file);
return stats.isDirectory();
} catch (err) {
return false;
}
}
function ifExists(file) {
return fs.existsSync(file) ? file : null;
}
async function check(input) {
const resolved = path.resolve(input);
const bundle = await rollup({
input: '__agadoo__',
plugins: [
virtual({
__agadoo__: `import ${JSON.stringify(resolved)}`,
tslib: `
const noop = () => {};
export const __awaiter = noop;
export const __extends = noop;
export const __generator = noop;
export const __spreadArrays = noop;
`,
}),
],
onwarn: (warning, handle) => {
if (warning.code !== 'EMPTY_BUNDLE') handle(warning);
},
});
const o = await bundle.generate({
format: 'es',
});
const output = o.output;
console.log(output);
return {
shaken: output.length === 1 && output[0].code.trim() === '',
};
}
main();