-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundler.js
74 lines (72 loc) · 1.88 KB
/
bundler.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
const fs = require("fs");
const path = require("path");
const babelParser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const babel = require("@babel/core");
let ID = 0;
function createAsset(filename) {
const content = fs.readFileSync(filename, "utf-8");
const ast = babelParser.parse(content, {
sourceType: "module",
});
const dependencies = [];
traverse(ast, {
ImportDeclaration: ({ node }) => {
dependencies.push(node.source.value);
},
});
const id = ID++;
const { code } = babel.transformFromAst(ast, null, {
presets: ["@babel/preset-env"],
});
return {
id,
filename,
dependencies,
code,
};
}
function buildDepsTree(entry) {
const mainAsset = createAsset(entry);
const queue = [mainAsset];
for (const asset of queue) {
const dirname = path.dirname(asset.filename);
// save dependencies to its path
asset.mapping = {};
asset.dependencies.forEach((relativePath) => {
const absolutePath = path.join(dirname, relativePath);
const childAsset = createAsset(absolutePath);
asset.mapping[relativePath] = childAsset.id;
queue.push(childAsset);
});
}
return queue;
}
function bundle(tree) {
let modules = "";
tree.forEach((node) => {
modules += `${node.id}: [
function(require,module,exports) {
${node.code}
},
${JSON.stringify(node.mapping)}
],`;
});
const result = `
(function(modules) {
function require(id) {
const [fn, mapping] = modules[id];
function localRequire(relativePath) {
return require(mapping[relativePath]);
}
const module = { exports: {} };
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({${modules}})
`;
return result;
}
const tree = buildDepsTree("./src/entry.js");
console.log(bundle(tree));