-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfoldin.js
309 lines (282 loc) · 9.45 KB
/
foldin.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
const fs = require("fs")
const path = require("path")
const babel = require("@babel/core")
const express = require("express")
function _build({ entryFile, htmlTemplatePath, outputFolder }) {
// build dependency graph
const graph = createDependencyGraph(entryFile)
// bundle the asset
const outputFiles = bundle(graph)
// write to bundle.js
for (const outputFile of outputFiles) {
fs.writeFileSync(path.join(outputFolder, outputFile.name), outputFile.content, "utf-8")
}
outputFiles.push(generateHTMLTemplate(htmlTemplatePath, outputFiles))
return { outputFiles, graph }
}
function _dev({ entryFile, outputFolder, htmlTemplatePath, devServerOptions }) {
const { outputFiles } = _build({ entryFile, htmlTemplatePath, outputFolder })
const outputFileMap = {}
for (const outputFile of outputFiles) {
outputFileMap[outputFile.name] = outputFile.content
}
const indexHtml = outputFileMap["index.html"]
const app = express()
app.use((req, res) => {
// trim off preceding slash '/'
const requestFile = req.path.slice(1)
if (outputFileMap[requestFile]) {
return res.send(outputFileMap[requestFile])
}
res.send(indexHtml)
})
app.listen(devServerOptions.port, () =>
console.log(`Dev server starts at http://localhost:${devServerOptions.port}`)
)
}
function createDependencyGraph(entryFile) {
const rootModule = createModule(entryFile)
return rootModule
}
const MODULE_CACHE = new Map()
function createModule(filePath) {
if (!MODULE_CACHE.has(filePath)) {
const fileExtension = path.extname(filePath)
const ModuleCls = MODULE_LOADERS[fileExtension]
if (!ModuleCls) {
throw new Error(`Unsupported extension "${fileExtension}".`)
}
const module = new ModuleCls(filePath)
MODULE_CACHE.set(filePath, module)
module.initDependencies()
}
return MODULE_CACHE.get(filePath)
}
class Module {
constructor(filePath) {
this.filePath = filePath
this.content = fs.readFileSync(filePath, "utf-8")
this.transform()
}
initDependencies() {
this.dependencies = []
}
transform() {}
transformModuleInterface() {}
}
class JSModule extends Module {
constructor(filePath) {
super(filePath)
this.ast = babel.parseSync(this.content)
}
initDependencies() {
this.dependencies = this.findDependencies()
}
findDependencies() {
const importDeclarations = this.ast.program.body.filter(
(node) => node.type === "ImportDeclaration"
)
const dependencies = []
for (const importDeclaration of importDeclarations) {
const requestPath = importDeclaration.source.value
const resolvedPath = resolveRequest(this.filePath, requestPath)
dependencies.push(createModule(resolvedPath))
//replace the request path to the resolved path
importDeclaration.source.value = resolvedPath
}
return dependencies
}
transformModuleInterface() {
const { types: t } = babel
const { filePath } = this
const { ast, code } = babel.transformFromAstSync(this.ast, this.content, {
ast: true,
plugins: [
function () {
return {
visitor: {
ImportDeclaration(path) {
const newIdentifier = path.scope.generateUidIdentifier("imported")
for (const specifier of path.get("specifiers")) {
const binding = specifier.scope.getBinding(specifier.node.local.name)
const importedKey = specifier.isImportDefaultSpecifier()
? "default"
: specifier.get("imported.name").node
for (const referencePath of binding.referencePaths) {
referencePath.replaceWith(
t.memberExpression(newIdentifier, t.stringLiteral(importedKey), true)
)
}
}
path.replaceWith(
t.variableDeclaration("const", [
t.variableDeclarator(
newIdentifier,
t.callExpression(t.identifier("require"), [path.get("source").node])
),
])
)
},
ExportDefaultDeclaration(path) {
path.replaceWith(
t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(t.identifier("exports"), t.identifier("default"), false),
t.toExpression(path.get("declaration").node)
)
)
)
},
ExportNamedDeclaration(path) {
const declarations = []
if (path.has("declaration")) {
if (path.get("declaration").isFunctionDeclaration()) {
declarations.push({
name: path.get("declaration.id").node,
value: t.toExpression(path.get("declaration").node),
})
} else {
path.get("declaration.declarations").forEach((declaration) => {
declarations.push({
name: declaration.get("id").node,
value: declaration.get("init").node,
})
})
}
} else {
path.get("specifiers").forEach((specifier) => {
declarations.push({
name: specifier.get("exported").node,
value: specifier.get("local").node,
})
})
}
path.replaceWithMultiple(
declarations.map((decl) =>
t.expressionStatement(
t.assignmentExpression(
"=",
t.memberExpression(t.identifier("exports"), decl.name, false),
decl.value
)
)
)
)
},
},
}
},
],
})
this.ast = ast
this.content = code
}
}
class CSSModule extends Module {
transform() {
this.content = trim(`
const content = '${this.content.replace(/\n/g, "")}';
const style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) style.styleSheet.cssText = content;
else style.appendChild(document.createTextNode(content));
document.head.appendChild(style);
`)
}
}
const MODULE_LOADERS = {
".css": CSSModule,
".js": JSModule,
}
// resolving
function resolveRequest(requester, requestPath) {
if (requestPath[0] === ".") {
// relative import
return path.join(path.dirname(requester), requestPath)
} else {
const requesterParts = requester.split("/")
const requestPaths = []
for (let i = requesterParts.length - 1; i > 0; i--) {
requestPaths.push(requesterParts.slice(0, i).join("/") + "/node_modules")
}
// absolute import
return require.resolve(requestPath, { paths: requestPaths })
}
}
// bundling
function bundle(graph) {
const modules = collectModules(graph)
const moduleMap = toModuleMap(modules)
const moduleCode = addRuntime(moduleMap, modules[0].filePath)
return [{ name: "bundle.js", content: moduleCode }]
}
function collectModules(graph) {
const modules = new Set()
collect(graph, modules)
return Array.from(modules)
function collect(module, modules) {
if (!modules.has(module)) {
modules.add(module)
module.dependencies.forEach((dependency) => collect(dependency, modules))
}
}
}
function toModuleMap(modules) {
let moduleMap = ""
moduleMap += "{"
for (const module of modules) {
module.transformModuleInterface()
moduleMap += `"${module.filePath}": function(exports, require) { ${module.content}\n },`
}
moduleMap += "}"
return moduleMap
}
function addRuntime(moduleMap, entryPoint) {
return trim(`
const modules = ${moduleMap};
const entry = "${entryPoint}";
function webpackStart({ modules, entry }) {
const moduleCache = {};
const require = moduleName => {
// if in cache, return the cached version
if (moduleCache[moduleName]) {
return moduleCache[moduleName];
}
const exports = {};
// this will prevent infinite "require" loop
// from circular dependencies
moduleCache[moduleName] = exports;
// "require"-ing the module,
// exported stuff will assigned to "exports"
modules[moduleName](exports, require);
return moduleCache[moduleName];
};
// start the program
require(entry);
}
webpackStart({ modules, entry });
`)
}
function trim(str) {
const lines = str.split("\n").filter(Boolean)
const padLength = lines[0].length - lines[0].trimLeft().length
const regex = new RegExp(`^\\s{${padLength}}`)
return lines.map((line) => line.replace(regex, "")).join("\n")
}
function generateHTMLTemplate(htmlTemplatePath, outputFiles) {
let htmlTemplate = fs.readFileSync(htmlTemplatePath, "utf-8")
htmlTemplate = htmlTemplate.replace(
"</body>",
outputFiles.map(({ name }) => `<script src="/${name}"></script>`).join("") + "</body>"
)
return { name: "index.html", content: htmlTemplate }
}
_dev({
entryFile: path.join(__dirname, "./src/index.js"),
outputFolder: path.join(__dirname, "./dist"),
htmlTemplatePath: path.join(__dirname, "./src/index.html"),
devServerOptions: {
port: 3005,
},
})