Created
May 14, 2023 07:29
-
-
Save RSamaium/b8c9605fa6f0cc56c01bcda0a46e20b3 to your computer and use it in GitHub Desktop.
code that automatically adds .js at the end of import/from
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
import { glob } from 'glob' | |
import { readFile, writeFile } from 'fs/promises' | |
import path from 'path'; | |
export function addFileExtension(importStatement) { | |
const staticImportRegex = /(import\s+(?:.+\s+from\s+)?['"])(\.\/[^'\"]+)(?<!\.js)(['"])/g; | |
const dynamicImportRegex = /(import\(['"])(\.\/[^'\"]+)(?<!\.js)(['"]\))/g; | |
const reexportRegex = /(export .+ from ['"])(\.\/[^'\"]+)(?<!\.js)(['"])/g; | |
importStatement = importStatement.replace(staticImportRegex, "$1$2.js$3"); | |
importStatement = importStatement.replace(dynamicImportRegex, "$1$2.js$3"); | |
importStatement = importStatement.replace(reexportRegex, "$1$2.js$3"); | |
return importStatement; | |
} | |
export async function getJsFiles(config = {}) { | |
let includePattern = config.include || '**/*.js'; | |
let excludePattern = config.exclude || []; | |
excludePattern.push('**/node_modules/**'); | |
excludePattern = excludePattern.length > 1 ? `{${excludePattern.join(',')}}` : excludePattern[0]; | |
const root = path.join(process.cwd(), config.rootDir) || ''; | |
const files = await glob(includePattern, { ignore: excludePattern, cwd: root }); | |
for (let f of files) { | |
const file = path.join(root, f); | |
const code = addFileExtension(await readFile(file, 'utf8')) | |
await writeFile(file, code) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment