Last active
April 17, 2024 09:13
-
-
Save brillout/79fd8b21e8893f92334b885ee9fa30ff to your computer and use it in GitHub Desktop.
CJS->ESM migration script: append `.js` to all imports
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*************************** | |
Script to append `.js` to the path of your imports. | |
Before: | |
```ts | |
// someTypeScriptFile.ts | |
import { something } from './some/module' | |
``` | |
After: | |
```ts | |
// someTypeScriptFile.ts | |
import { something } from './some/module.js' | |
``` | |
This script doesn't remove directory imports, you'll have to do that manually. | |
****************************/ | |
import { execSync } from 'child_process' | |
import fs from 'fs' | |
// Function to append ".js" to ESM imports in a given TypeScript file | |
const appendJsToESMImports = (filePath) => { | |
console.log('filePath', filePath) | |
// Read the content of the file | |
let content = fs.readFileSync(filePath, 'utf8') | |
const patterns = [ | |
// | |
/import(.+)from ['"](\.[^'"]+)['"]/g, | |
/export(.+)from ['"](\.[^'"]+)['"]/g, | |
] | |
patterns.forEach((pattern) => { | |
content = content.replace(pattern, (importStatement, _, importPath) => { | |
if (importPath.endsWith('.js')) return | |
const newImportPath = importPath + '.js' | |
console.log('newImportPath', newImportPath) | |
return importStatement.replace(importPath, newImportPath) | |
}) | |
}) | |
// Write the modified content back to the file | |
fs.writeFileSync(filePath, content, 'utf8') | |
} | |
// Get the list of TypeScript files in the current Git repository | |
const gitFiles = execSync('git ls-files "*.ts" "*.tsx"').toString().split('\n').filter(Boolean) | |
// Apply the import modification to each TypeScript file | |
gitFiles.forEach((filePath) => { | |
appendJsToESMImports(filePath) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment