You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron中如何使用__dirname?解决__dirname未定义报错

解决Electron中__dirname is not defined的问题

情况1:主进程使用ES模块(package.json含"type": "module")

ES模块环境下默认没有__dirname,可手动通过Node.js的url和path模块定义:

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

情况2:主进程使用CommonJS模块

CommonJS环境下__dirname默认可用,若仍报错,检查是否误开启了ES模块模式(比如package.json设置了"type": "module"),移除该配置即可恢复默认行为。

情况3:渲染进程中使用__dirname

出于安全考虑,Electron 12+默认关闭nodeIntegration并开启contextIsolation,渲染进程无法直接访问Node.js变量。推荐通过预加载脚本注入:

  1. 编写预加载脚本preload.js:
const { contextBridge } = require('electron');
const path = require('path');

contextBridge.exposeInMainWorld('appUtils', {
  getDirname: () => __dirname
});
  1. 主进程创建窗口时配置预加载路径:
const { BrowserWindow } = require('electron');
const path = require('path');

const mainWindow = new BrowserWindow({
  webPreferences: {
    preload: path.join(__dirname, 'preload.js'),
    contextIsolation: true, // 保持开启,保障安全
    nodeIntegration: false
  }
});
  1. 渲染进程中调用:
const currentDir = window.appUtils.getDirname();

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:10:26