From 57e093d734e4b81bbeeecbd694b269cca698f914 Mon Sep 17 00:00:00 2001 From: qmhc <544022268@qq.com> Date: Fri, 30 Sep 2022 20:49:51 +0800 Subject: [PATCH] fix: patch cjs vars for esm scope fix #119, fix #122 --- scripts/build.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/scripts/build.ts b/scripts/build.ts index 07c879e..c66609e 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -13,6 +13,11 @@ async function main() { { stdio: 'inherit' } ) + await patchCommomJs() + await patchESModule() +} + +async function patchCommomJs() { const indexPath = path.resolve(root, '../dist/index.cjs') let indexCodes = await fs.readFile(indexPath, 'utf-8') @@ -31,6 +36,24 @@ async function main() { } } +const cjsBridge = ` +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); +` + +async function patchESModule() { + const indexPath = path.resolve(root, '../dist/index.mjs') + + let indexCodes = await fs.readFile(indexPath, 'utf-8') + indexCodes = cjsBridge + indexCodes + + await fs.writeFile(indexPath, indexCodes) +} + main().catch(error => { console.error(error) process.exit(1)