-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
108 lines (85 loc) · 2.49 KB
/
index.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const fs = require('fs');
const path = require('path');
const babylon = require('babylon');
const traverse = require('babel-traverse').default;
const babel = require('babel-core');
const BundlerFactory = (startID = 0) => {
let ID = startID;
return (config = {}) => {
const createAsset = (filename) => {
try {
const content = fs.readFileSync(filename, 'utf-8');
const ast = babylon.parse(content, {
sourceType: 'module',
});
const dependencies = [];
traverse(ast, {
ImportDeclaration: ({ node }) => {
dependencies.push(node.source.value);
}
});
const { code } = babel.transformFromAst(ast, null, {
presets: ['env'],
})
return {
id: ID++,
filename,
dependencies,
code,
};
} catch (err) {
console.error(err);
}
};
const 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;
};
const bundle = (graph) => {
let modules = '';
graph.forEach(mod => {
// fn + dependencies mapping
modules += `${mod.id}: [
function (require, module, exports) {
${mod.code}
},
${JSON.stringify(mod.mapping)}
],`;
});
const result = `(function(modules) {
function require(id) {
const [fn, mapping] = modules[id];
// construct 'require', 'module' and 'exports'
function localRequire(relativePath) {
// require recursion
return require(mapping[relativePath]);
}
const module = { exports: {} };
// bind code to module.exports
fn(localRequire, module, module.exports);
return module.exports;
}
require(0);
})({${modules}})`;
return result;
}
const bundler = (entry) => {
return bundle(createGraph(entry));
}
return bundler;
}
};
const factory = BundlerFactory();
const bundler = factory();
console.log(bundler('./tests/a.js'));