Module bundler — combine multiple files into one.
1const fs = require("fs");2const path = require("path");34class SimpleBundler {5 constructor(entry) {6 this.entry = entry;7 this.modules = new Map();8 this.queue = [entry];9 }1011 async bundle() {12 while (this.queue.length > 0) {13 const modulePath = this.queue.shift();14 if (this.modules.has(modulePath)) continue;1516 const code = fs.readFileSync(modulePath, "utf8");17 const dependencies = this.extractDependencies(code, modulePath);1819 this.modules.set(modulePath, { code, dependencies });20 dependencies.forEach(dep => this.queue.push(dep));21 }2223 return this.generateBundle();24 }2526 extractDependencies(code, filePath) {27 const regex = /require\(["'](.+?)["']\)/g;28 const deps = [];29 let match;3031 while ((match = regex.exec(code)) !== null) {32 const depPath = path.resolve(path.dirname(filePath), match[1]);33 deps.push(depPath);34 }3536 return deps;37 }3839 generateBundle() {40 const modules = [];41 this.modules.forEach((module, id) => {42 modules.push(`"${id}": function(module, exports, require) {43 ${module.code}44 }`);45 });4647 return `48(function(modules) {49 function require(id) {50 const module = { exports: {} };51 modules[id](module, module.exports, require);52 return module.exports;53 }54 require("${this.entry}");55})({56 ${modules.join(",\n")}57});58`;59 }60}6162// Usage63const bundler = new SimpleBundler("./src/index.js");64const bundle = await bundler.bundle();65fs.writeFileSync("dist/bundle.js", bundle);