This repository was archived by the owner on Apr 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathtreeshaking.js
More file actions
96 lines (79 loc) · 1.96 KB
/
treeshaking.js
File metadata and controls
96 lines (79 loc) · 1.96 KB
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
const path = require('path');
const { rollup } = require('rollup');
const virtual = require('rollup-plugin-virtual');
const fs = require('fs');
function main() {
const input = process.argv[2] || get_input();
check(input).then(result => {
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 get_input() {
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 (is_directory(file)) {
return if_exists(`${file}/index.mjs`) || if_exists(`${file}/index.js`);
}
return if_exists(file) || if_exists(`${file}.mjs`) || if_exists(`${file}.js`);
}
function is_directory(file) {
try {
const stats = fs.statSync(file);
return stats.isDirectory();
} catch (err) {
return false;
}
}
function if_exists(file) {
return fs.existsSync(file) ? file : null;
}
const check = input => {
const resolved = path.resolve(input);
return rollup({
input: '__agadoo__',
plugins: [
virtual({
__agadoo__: `import ${JSON.stringify(resolved)}`
}),
{
resolveId(id) {
if (!id.startsWith('.') && !id.startsWith('/')) {
return {id: id, external: true, moduleSideEffects: false};
}
return null;
}
}
],
onwarn: (warning, handle) => {
if (warning.code !== 'EMPTY_BUNDLE') handle(warning);
}
}).then(bundle => bundle.generate({
format: 'es'
})).then(o => {
const output = o.output;
console.log(output);
return {
shaken: output.length === 1 && output[0].code.trim() === ''
};
});
};
main();