Question 39
Question
Answer
// Simplified Bundler Example (Conceptual)
class CustomBundler {
constructor(entryPoint) {
this.entryPoint = entryPoint; // Main module to start bundling from
this.modules = {}; // Store loaded modules
}
async bundle() {
await this._loadModule(this.entryPoint);
// After loading dependencies recursively, generate the bundled output:
const bundledCode = `
import('${this.entryPoint}'); // Start with entry point
${Object.values(this.modules).map((module) => module.code)} // Include other modules
`;
console.log(bundledCode);
}
async _loadModule(moduleName) {
try {
const module = await import(moduleName); // Dynamically load the module
this.modules[moduleName] = {
name: moduleName,
code: module.default || module.toString(), // Get module's code
dependencies: module.exports ? Object.keys(module.exports) : [],
};
// Recursively load dependencies
for (const dependency of this.modules[moduleName].dependencies) {
await this._loadModule(dependency);
}
} catch (error) {
console.error(`Error loading module '${moduleName}':`, error);
}
}
}
// Usage example:
const bundler = new CustomBundler('./src/index.js');
bundler.bundle(); // Start the bundling processLast updated