Skip to content

Instantly share code, notes, and snippets.

@coderbyheart
Last active February 10, 2025 10:11
Migrate from TSX to native Node.js TypeScript running
import fs from 'node:fs'
import path, { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = dirname(fileURLToPath(import.meta.url))
console.log(__dirname) // Outputs: /absolute/path/to/directory
const updateImports = (directory) =>
fs.readdirSync(directory).forEach((file) => {
const filePath = path.join(directory, file)
if (fs.statSync(filePath).isDirectory()) {
if (file === 'node_modules') return
updateImports(filePath)
} else if (filePath.endsWith('.ts') || filePath.endsWith('.tsx')) {
let content = fs.readFileSync(filePath, 'utf8')
content = content.replace(/from ['"](.+?)\.jsx['"]/g, "from '$1.tsx'")
content = content.replace(/from ['"](.+?)\.js['"]/g, "from '$1.ts'")
fs.writeFileSync(filePath, content)
console.log(filePath)
}
})
updateImports(__dirname)
curl https://gist.githubusercontent.com/coderbyheart/ba41fa4a5b0e06854ac9e2e5068be052/raw/8c8ed5f852e0d36c64e5fa1caf9e430f341bb811/convert-imports.js > convert-imports.js
node convert-imports.js
rm convert-imports.js
jq '.compilerOptions.allowImportingTsExtensions = true' tsconfig.json > tmp.json && mv tmp.json tsconfig.json
jq '.engines.node = ">=22.7.0"' package.json > tmp.json && mv tmp.json package.json
npm uninstall --save tsx
# Change all occurences of `npm tsx`, `node --loader tsx`, and `tsx` to `node --experimental-transform-types`
# Get rid of `npx globstar -- `, because the Node.js testrunner supports glob now natively.
npm uninstall --save globstar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment