You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

在Aurelia骨架项目中导入Electron.remote遇fs.js找不到错误求助

解决Electron.remote导入及fs路径错误问题

我来帮你搞定这个问题~你遇到的fs路径找不到错误,主要是因为Electron的主进程和渲染进程API是分离的,直接导入整个electron包会把主进程专属的模块(比如fs)带到渲染进程里,而jspm的配置没正确区分这一点;另外从Electron 14开始,remote模块默认是禁用的,也需要额外配置启用。

下面是具体的解决步骤:

1. 先启用Electron Remote模块(Electron 14+必做)

首先安装官方的@electron/remote包(原来的electron.remote已经移到这个独立包了):

npm install @electron/remote

然后在你的Electron主进程文件(比如main.js)里初始化并启用remote:

const { app, BrowserWindow } = require('electron');
const remoteMain = require('@electron/remote/main');

// 初始化remote模块
remoteMain.initialize();

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      // 注意:这里要开启nodeIntegration和关闭contextIsolation(适配remote模块)
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  // 给当前窗口启用remote权限
  remoteMain.enable(mainWindow.webContents);

  // 加载你的应用页面
  mainWindow.loadURL('your-app-url');
}

app.whenReady().then(() => {
  createWindow();
});

2. 调整jspm配置,避免导入整个electron包

修改你的config.js,不要映射整个electron包,而是直接映射@electron/remote

paths: {
  "*": "dist/*",
  "github:*": "jspm_packages/github/*",
  "npm:*": "jspm_packages/npm/*",
  "node_modules:*": "node_modules/*"
},
map: {
  "@electron/remote": "node_modules:@electron/remote/index.js"
}

3. 在渲染进程中正确导入并关闭窗口

现在在你的JS文件里,直接导入@electron/remote,然后获取当前窗口关闭:

import * as remote from '@electron/remote';

// 关闭当前窗口的函数
function closeWindow() {
  const currentWindow = remote.getCurrentWindow();
  currentWindow.close();
}

// 绑定到按钮或者事件上使用
document.getElementById('close-btn').addEventListener('click', closeWindow);

额外注意事项

  • 确保你的Electron版本和@electron/remote版本兼容:比如Electron 14对应@electron/remote 2.x,Electron 20+对应更高版本
  • 不要在渲染进程中导入整个electron包,因为里面包含主进程才能访问的模块(比如fs、path),会导致路径错误
  • 检查jspm的node_modules:*路径是否正确指向你的项目根目录下的node_modules文件夹

内容的提问来源于stack exchange,提问作者Ben Chiciudean

火山引擎 最新活动