From 819b5019dd5e894fd6d03622421bdd23e82d07e7 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Thu, 9 Nov 2023 15:42:35 +0100 Subject: [PATCH] meta: import js2ts script - add `@ts-ignore` comment on `package.json` imports. - better detect imports of local `.js` files. - do not remove non-JS files from the source. --- private/js2ts/index.mjs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/private/js2ts/index.mjs b/private/js2ts/index.mjs index 961180def2..266a9540e4 100755 --- a/private/js2ts/index.mjs +++ b/private/js2ts/index.mjs @@ -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)