bundler.js


SUBMITTED BY: okpalan86

DATE: Feb. 19, 2024, 8:32 p.m.

UPDATED: Feb. 19, 2024, 8:49 p.m.

FORMAT: Text only

SIZE: 1.4 kB

HITS: 608

  1. const fs = require('fs');
  2. const path = require('path');
  3. function bundle(entryFile) {
  4. const entryContent = fs.readFileSync(entryFile, 'utf8');
  5. const modules = {};
  6. function require(modulePath) {
  7. const fullPath = path.resolve(__dirname, modulePath);
  8. if (modules[fullPath]) {
  9. return modules[fullPath].exports;
  10. }
  11. const module = { exports: {} };
  12. modules[fullPath] = module;
  13. // Execute the module code with `require`, `module`, and `exports`
  14. // available as local variables.
  15. const moduleCode = fs.readFileSync(fullPath, 'utf8');
  16. const wrappedCode = `(function (require, module, exports, __dirname, __filename) { ${moduleCode} })(require, module, module.exports, "${path.dirname(fullPath)}", "${fullPath}")`;
  17. eval(wrappedCode);
  18. return module.exports;
  19. }
  20. require(entryFile);
  21. // Create the bundle
  22. const bundledCode = Object.keys(modules)
  23. .map(modulePath => {
  24. const moduleName = JSON.stringify(path.relative(__dirname, modulePath));
  25. const moduleContent = modules[modulePath].exports.toString();
  26. return `// ${moduleName}\n${moduleContent}`;
  27. })
  28. .join('\n\n');
  29. return bundledCode;
  30. }
  31. const entryFile = path.resolve(__dirname,'src/index.js'); // Update this with your entry file
  32. const bundledCode = bundle(entryFile);
  33. fs.writeFileSync('./bundle.js', bundledCode, 'utf8');

comments powered by Disqus