is-elevated使用中CommonJS/ESM不兼容导致的错误,两种修法
is-elevated不兼容导致的错误,两种修法这是 CommonJS/ESM 不兼容导致的。is-elevated 新版是 ESM-only,不能用 require()。两种修法:方案A:改成动态 import(保留 CommonJS)
// main.js(主进程)
const { app } = require('electron');
const { spawn } = require('child_process');
async function relaunchAsAdminIfNeeded() {
if (process.platform !== 'win32') return;
// ESM 动态导入
const { default: isElevated } = await import('is-elevated');
if (await isElevated()) return;
const args = process.argv.slice(1).map(a => `"${a.replace(/"/g, '\\"')}"`).join(' ');
const ps = [
'-NoProfile','-ExecutionPolicy','Bypass','-Command',
`Start-Process -FilePath "${process.execPath}" -ArgumentList '${args.replace(/'/g,"''")}' -Verb RunAs`
];
spawn('powershell.exe', ps, { detached: true, windowsHide: true });
app.quit();
}
app.whenReady().then(relaunchAsAdminIfNeeded).catch(console.error);
process.on('unhandledRejection', console.error);方案B:改用 CommonJS 版本的 is-elevated
npm i is-elevated@3然后继续用:const isElevated = require('is-elevated'); // 返回 Promise<boolean>// ...existing code...
const { app, BrowserWindow } = require('electron');
const { spawn } = require('child_process');
const isElevated = require('is-elevated'); // 关键:引入
async function relaunchAsAdminIfNeeded() {
if (process.platform !== 'win32') return;
if (await isElevated()) return;
const args = process.argv.slice(1).map(a => `"${a.replace(/"/g, '\\"')}"`).join(' ');
const ps = [
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command',
`Start-Process -FilePath "${process.execPath}" -ArgumentList '${args.replace(/'/g, "''")}' -Verb RunAs`
];
spawn('powershell.exe', ps, { detached: true, windowsHide: true });
app.quit();
}
app.whenReady()
.then(() => relaunchAsAdminIfNeeded())
.catch(err => console.error('elevate failed:', err));
// 可选:兜底,避免未处理的 Promise 报警
process.on('unhandledRejection', err => console.error(err));
// ...existing code...备注
[*]不要在 CommonJS 里用 import 静态语法,需用动态 import() 或把整个项目改成 ESM(package.json 加 "type":"module")。
页:
[1]