From 6241ad11b9ef822b127ffc171d811d518b4631bc Mon Sep 17 00:00:00 2001 From: wiiiii123 Date: Fri, 8 May 2026 00:07:23 +0700 Subject: [PATCH] fix(electron): strip import.meta from cjs bundle --- scripts/normalize-electron-main-cjs.mjs | 27 ++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/scripts/normalize-electron-main-cjs.mjs b/scripts/normalize-electron-main-cjs.mjs index f5886aef..4e85495a 100644 --- a/scripts/normalize-electron-main-cjs.mjs +++ b/scripts/normalize-electron-main-cjs.mjs @@ -2,6 +2,7 @@ import fs from "node:fs/promises"; import { pathToFileURL } from "node:url"; const mainBundleUrl = new URL("../dist-electron/main.cjs", import.meta.url); +const IMPORT_META_URL_CJS_REPLACEMENT = 'require("node:url").pathToFileURL(__filename).href'; function convertNamedImports(namedSpec) { return namedSpec.replace(/\s+as\s+/g, ": "); @@ -35,9 +36,7 @@ function convertImportLine(line) { return `${indent}const ${spec} = require(${moduleLiteral});`; } - const sideEffectImportMatch = line.match( - /^([ \t]*)import\s+(["'][^"']+["'])\s*;?[ \t]*$/, - ); + const sideEffectImportMatch = line.match(/^([ \t]*)import\s+(["'][^"']+["'])\s*;?[ \t]*$/); if (sideEffectImportMatch) { const [, indent, moduleLiteral] = sideEffectImportMatch; return `${indent}require(${moduleLiteral});`; @@ -130,8 +129,16 @@ export function normalizeElectronMainCjsSource(source) { } } - normalizedLines.push(line); - state = updateLexicalState(line, state); + const normalizedLine = line.replace( + /\bimport\.meta\.url\b/g, + IMPORT_META_URL_CJS_REPLACEMENT, + ); + if (normalizedLine !== line) { + changed = true; + } + + normalizedLines.push(normalizedLine); + state = updateLexicalState(normalizedLine, state); } if (!changed) { @@ -159,6 +166,13 @@ export function findElectronMainCjsEsmSyntax(source) { }); continue; } + if (/\bimport\.meta\b/.test(line)) { + matches.push({ + line: index + 1, + text: line.trim(), + }); + continue; + } } state = updateLexicalState(line, state); @@ -183,8 +197,7 @@ export async function normalizeElectronMainCjs(bundleUrl = mainBundleUrl) { return normalized; } -const isDirectRun = - process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; +const isDirectRun = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href; if (isDirectRun) { const result = await normalizeElectronMainCjs();