UNPKG

beesbuild

Version:

构建工具链

42 lines (40 loc) 1.14 kB
import { findStaticImports } from "mlly"; import MagicString from "magic-string"; function cjsPlugin(option, ctx) { if ((option != null ? option : false) === false) return []; return { name: "cli-cjs", renderChunk(code, _chunk, opts) { if (opts.format === "es") { return CJSToESM(code); } return null; } }; } const CJSyntaxRe = /__filename|__dirname|require\(|require\.resolve\(/; const CJSShim = ` // -- Unbuild CommonJS Shims -- import __cjs_url__ from 'url'; import __cjs_path__ from 'path'; import __cjs_mod__ from 'module'; const __filename = __cjs_url__.fileURLToPath(import.meta.url); const __dirname = __cjs_path__.dirname(__filename); const require = __cjs_mod__.createRequire(import.meta.url); `; function CJSToESM(code) { if (code.includes(CJSShim) || !CJSyntaxRe.test(code)) { return null; } const lastESMImport = findStaticImports(code).pop(); const indexToAppend = lastESMImport ? lastESMImport.end : 0; const s = new MagicString(code); s.appendRight(indexToAppend, CJSShim); return { code: s.toString(), map: s.generateMap() }; } export { cjsPlugin };