Skip to content

Instantly share code, notes, and snippets.

@saurabhshri
Last active July 7, 2022 06:50
Show Gist options
  • Save saurabhshri/4c0e13f09232dd8c863908763084e709 to your computer and use it in GitHub Desktop.
Save saurabhshri/4c0e13f09232dd8c863908763084e709 to your computer and use it in GitHub Desktop.
Add .js extension to all relative ESM imports since typescript won't do it. Modified version of https://github.com/microsoft/TypeScript/issues/16577#issuecomment-310426634 . WARNING: Doesn't work on multiline imports, please verify all files after script run.

WARNING: Doesn't work on multiline imports, please verify all files after script run. Modified version of microsoft/TypeScript#16577 (comment) .

Add .js extension to all relative ESM imports since typescript won't do it.

Usage

  1. Set REPO_PATH env variable to list of paths (comma separated) to read .ts files from.
REPO_PATH=/Users/saurabhshri/IdeaProjects/{project-name}/src/,/Users/saurabhshri/IdeaProjects/{project-name}/tests
  1. Run the script.
npm install
node add-js-extension-esm-relative-imports.js
"use strict";
const FileHound = require('filehound');
const fs = require('fs');
const paths = process.env.REPO_PATH
? process.env.REPO_PATH.split(",").map(path => path.trim())
: (function () {
throw new Error("set REPO_PATH to comma separated input path lists");
})();
console.warn("Does not handle multi-line imports, verify after script run. Use at your own risk");
console.log("Processing repository on paths : ", paths);
const files = FileHound.create()
.paths(paths)
.ext('ts')
.find();
files.then((filePaths) => {
filePaths.forEach((filepath) => {
fs.readFile(filepath, 'utf8', (err, data) => {
let newContent = data.split("\n")
.map(line => {
if (!line.startsWith("import")) {
return line;
}
const tokens = line.split(" ");
let modulePath = tokens.pop();
if (modulePath.startsWith("\"/") || modulePath.startsWith("\"./") || modulePath.startsWith("\"../")) {
if (modulePath.endsWith(";")) {
modulePath = `${modulePath.slice(0, -2)}.js";`
} else {
modulePath = `${modulePath.slice(0, -1)}.js";`
}
}
return [...tokens, modulePath].join(" ");
})
.join("\n");
console.log(`writing to ${filepath}`)
fs.writeFile(`${filepath}`, newContent, function (err) {
if (err) {
throw err;
}
console.log(`complete ${filepath}`);
});
});
})
});
{
"name": "add-js-extension-esm-relative-imports",
"version": "1.0.0",
"dependencies": {
"filehound": "^1.17.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment