forked from imteekay/frontend-infrastructure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbundler.js
94 lines (72 loc) · 1.89 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const fs = require('fs');
const path = require('path');
const parser = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const babel = require('@babel/core');
let ID = 0;
function createAsset(filename) {
const content = fs.readFileSync(path.resolve(__dirname, filename), 'utf-8');
const ast = parser.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/env'],
});
return {
id,
filename,
dependencies,
code,
};
}
function createGraph(entry) {
const mainAsset = createAsset(entry);
const queue = [mainAsset];
for (const asset of queue) {
const dirname = path.dirname(asset.filename);
asset.mapping = {};
asset.dependencies.forEach((relativePath) => {
const absolutePath = path.join(dirname, relativePath);
const child = createAsset(absolutePath);
asset.mapping[relativePath] = child.id;
queue.push(child);
});
}
return queue;
}
function bundle(graph) {
let modules = '';
graph.forEach((module) => {
modules += `${module.id}: [
function (require, module, exports) {
${module.code}
},
${JSON.stringify(module.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 graph = createGraph('./example/entry.js');
const result = bundle(graph);
console.log(result);