Skip to content

Commit

Permalink
meta: import js2ts script
Browse files Browse the repository at this point in the history
- add `@ts-ignore` comment on `package.json` imports.
- better detect imports of local `.js` files.
- do not remove non-JS files from the source.
  • Loading branch information
aduh95 committed Nov 9, 2023
1 parent 70ffe60 commit 819b501
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions private/js2ts/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,20 @@ for await (const dirent of dir) {
if (!dirent.isDirectory()) {
const { path: filepath } = dirent
const ext = extname(filepath)
if (ext !== '.js' && ext !== '.jsx') continue // eslint-disable-line no-continue
await writeFile(
filepath.replace(ext, ext.replace('js', 'ts')),
filepath.slice(0, -ext.length) + ext.replace('js', 'ts'),
(await readFile(filepath, 'utf-8')).replace(
/((?:^|\n)import[^\n]*["']\.\.?\/[^'"]+\.)js(x?["'])/g,
// The following regex aims to capture all imports and reexports of local .js(x) files to replace it to .ts(x)
// It's far from perfect and will have false positives and false negatives.
/((?:^|\n)(?:import(?:\s+\w+\s*from)?|(?:import|export) \{[^}]*\}\s*from)\s*["']\.\.?\/[^'"]+\.)js(x?["'])/g,
'$1ts$2',
).replace(
// The following regex aims to capture all local package.json imports.
/\nimport \w+ from ['"]..\/([^'"]+\/)*package.json['"]\n/g,
(originalImport) =>
`// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n` +
`// @ts-ignore We don't want TS to generate types for the package.json${originalImport}`,
),
)
await rm(filepath)
Expand Down

0 comments on commit 819b501

Please sign in to comment.