add-js-extensions.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. var __importStar = (this && this.__importStar) || function (mod) {
  3. if (mod && mod.__esModule) return mod;
  4. var result = {};
  5. if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
  6. result["default"] = mod;
  7. return result;
  8. };
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. const ts = __importStar(require("typescript"));
  11. const fs_1 = require("fs");
  12. const path_1 = require("path");
  13. /**
  14. * Script that adds .js extension to imports so that it's compatible with plain
  15. * browser/non-webpack bundlers. TS doesn't support this natively yet.
  16. * @see https://github.com/microsoft/TypeScript/issues/16577
  17. */
  18. function processFile(file) {
  19. let source = fs_1.readFileSync(file, 'utf-8');
  20. const program = ts.createSourceFile(path_1.basename(file), source, ts.ScriptTarget.ES2015, true);
  21. let offset = 0;
  22. const process = (node) => {
  23. if ((!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) || !node.moduleSpecifier) {
  24. return ts.forEachChild(node, process);
  25. }
  26. const specifier = node.moduleSpecifier;
  27. if (path_1.extname(specifier.getText()) === '') {
  28. const idx = specifier.end + offset - 1;
  29. source = source.slice(0, idx) + '.js' + source.slice(idx);
  30. offset += 3;
  31. }
  32. };
  33. process(program);
  34. fs_1.writeFileSync(file, source);
  35. }
  36. function processDir(dir) {
  37. const entries = fs_1.readdirSync(dir);
  38. for (const entry of entries) {
  39. const path = path_1.join(dir, entry);
  40. if (path.endsWith('.js')) {
  41. processFile(path);
  42. }
  43. else if (fs_1.statSync(path).isDirectory()) {
  44. processDir(path);
  45. }
  46. }
  47. }
  48. processDir(path_1.resolve(__dirname, '..', '..', 'esm'));
  49. //# sourceMappingURL=add-js-extensions.js.map