Skip to content

Instantly share code, notes, and snippets.

@akramsaouri
Created November 9, 2019 00:43
Show Gist options
  • Save akramsaouri/812867a0a7b71b739964c470cf35c4ae to your computer and use it in GitHub Desktop.
Save akramsaouri/812867a0a7b71b739964c470cf35c4ae to your computer and use it in GitHub Desktop.
Smaller es6 bundler possible
const fs = require("fs");
const path = require("path");
const parser = require("@babel/parser");
const traverse = require("@babel/traverse").default;
const babel = require("@babel/core");
const resolve = require("resolve").sync;
let ID = -1;
function createModuleInfo(filePath) {
const content = fs.readFileSync(filePath, "utf-8");
const ast = parser.parse(content, {
sourceType: 'module'
})
const deps = []
traverse(ast, {
ImportDeclaration: ({ node }) => {
deps.push(node.source.value)
}
})
ID++
const { code } = babel.transformFromAstSync(ast, null, {
presets: ["@babel/preset-env"]
})
return {
id: ID,
filePath,
deps,
code
}
}
function createDependencyGraph(entry) {
const entryInfo = createModuleInfo(entry)
const graphArr = [entryInfo]
for (const module of graphArr) {
module.map = {}
module.deps.forEach(depPath => {
const baseDir = path.dirname(module.filePath)
const moduleDepPath = resolve(depPath, { baseDir })
const moduleInfo = createModuleInfo(moduleDepPath)
graphArr.push(moduleInfo)
module.map[depPath] = moduleInfo.id
})
}
return graphArr
}
function pack(graph) {
const moduleArgArr = graph.map(module => {
return `${module.id}: {
factory: (exports, require) => {
${module.code}
},
map: ${JSON.stringify(module.map)}
}`
})
const iifeBundler = `(function(modules){
const require = id => {
const { factory, map } = modules[id]
const localRequire = requireDeclarationName => require(map[requireDeclarationName])
const module = { exports:{}}
factory(module.exports, localRequire)
return module.exports
}
require(0)
})({${moduleArgArr.join()}})`
return iifeBundler
}
const graph = createDependencyGraph("./entry.js");
const bundle = pack(graph);
console.log(bundle); // copy code and paste it into browser
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment