UNPKG

@reliverse/rse-sdk

Version:

@reliverse/rse-sdk allows you to create new plugins for @reliverse/rse CLI, interact with reliverse.org, and even extend your own CLI functionality (you may also try @reliverse/dler-sdk for this case).

31 lines (30 loc) 1.25 kB
import path from "@reliverse/pathkit"; import fs from "@reliverse/relifso"; import { relinka } from "@reliverse/relinka"; import { glob } from "tinyglobby"; export async function convertCjsToEsm(projectPath) { relinka("info", `Converting CommonJS to ESM in ${projectPath}`); const files = await glob("**/*.{js,jsx,ts,tsx}", { cwd: path.resolve(projectPath) }); for (const file of files) { const filePath = path.join(projectPath, file); const content = await fs.readFile(filePath, "utf-8"); let updatedContent = content; updatedContent = updatedContent.replace( /(?:const|let|var)\s*{\s*([^}]+)}\s*=\s*require\(['"]([^'"]+)['"]\)/g, 'import { $1 } from "$2"' ).replace( /(?:const|let|var)\s+(\w+)\s*=\s*require\(['"]([^'"]+)['"]\)/g, 'import $1 from "$2"' ); updatedContent = updatedContent.replace(/module\.exports\s*=\s*([^;\n]+)/g, "export default $1").replace( /module\.exports\.(\w+)\s*=\s*([^;\n]+)/g, "export const $1 = $2" ).replace(/exports\.(\w+)\s*=\s*([^;\n]+)/g, "export const $1 = $2"); if (content !== updatedContent) { await fs.writeFile(filePath, updatedContent, "utf-8"); relinka("info", `Converted ${filePath} to ESM`); } } }