Skip to content

Instantly share code, notes, and snippets.

@RSamaium
Created May 14, 2023 07:29
Show Gist options
  • Save RSamaium/b8c9605fa6f0cc56c01bcda0a46e20b3 to your computer and use it in GitHub Desktop.
Save RSamaium/b8c9605fa6f0cc56c01bcda0a46e20b3 to your computer and use it in GitHub Desktop.
code that automatically adds .js at the end of import/from
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