add-js-extensions.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import * as ts from 'typescript.js';
  2. import { readFileSync, writeFileSync, readdirSync, statSync } from 'fs.js';
  3. import { extname, basename, join, resolve } from 'path.js';
  4. /**
  5. * Script that adds .js extension to imports so that it's compatible with plain
  6. * browser/non-webpack bundlers. TS doesn't support this natively yet.
  7. * @see https://github.com/microsoft/TypeScript/issues/16577
  8. */
  9. function processFile(file) {
  10. let source = readFileSync(file, 'utf-8');
  11. const program = ts.createSourceFile(basename(file), source, ts.ScriptTarget.ES2015, true);
  12. let offset = 0;
  13. const process = (node) => {
  14. if ((!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) || !node.moduleSpecifier) {
  15. return ts.forEachChild(node, process);
  16. }
  17. const specifier = node.moduleSpecifier;
  18. if (extname(specifier.getText()) === '') {
  19. const idx = specifier.end + offset - 1;
  20. source = source.slice(0, idx) + '.js' + source.slice(idx);
  21. offset += 3;
  22. }
  23. };
  24. process(program);
  25. writeFileSync(file, source);
  26. }
  27. function processDir(dir) {
  28. const entries = readdirSync(dir);
  29. for (const entry of entries) {
  30. const path = join(dir, entry);
  31. if (path.endsWith('.js')) {
  32. processFile(path);
  33. }
  34. else if (statSync(path).isDirectory()) {
  35. processDir(path);
  36. }
  37. }
  38. }
  39. processDir(resolve(__dirname, '..', '..', 'esm'));
  40. //# sourceMappingURL=add-js-extensions.js.map