Uncaught ReferenceError: __dirname is not defined
at eval (index.js?bdb9:4)
at Object../node_modules/electron/index.js (chunk-vendors.js:1057)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (App.vue?234e:40)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/App.vue?vue&type=script&lang=js& (app.js:938)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (App.vue?c53a:1)
at Module../src/App.vue?vue&type=script&lang=js& (app.js:1029)
渲染进程属于浏览器端,没有集成Node的环境
创建渲染进程时,开启node环境,将 nodeIntegration
设置为 true
win = new BrowserWindow({
frame: false,
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
开启后,依然报如下错误:
Uncaught TypeError: fs.existsSync is not a function
at getElectronPath (index.js?bdb9:7)
at eval (index.js?bdb9:18)
at Object../node_modules/electron/index.js (chunk-vendors.js:1057)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (App.vue?234e:40)
at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/App.vue?vue&type=script&lang=js& (app.js:938)
at __webpack_require__ (app.js:849)
at fn (app.js:151)
at eval (App.vue?c53a:1)
衍生问题解决方案
创建 preload.js
文件,并在 创建渲染进程时的 webPreferen中设置预加载preload:
win = new BrowserWindow({
frame: false,
width: 800,
height: 600,
webPreferences: {
// nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
nodeIntegration: false,
preload: __dirname + '\\..\\src\\preload.js'
preload.js
文件代码如下:
window.remote = require('electron').remote;
并且将渲染进程的js文件中的JavaScript代码修改如下:
// 将此行代码替换为下面一行,不要使用require
// let { remote } = require('electron');
const remote = window.remote;
特别说明:因为运行后的根目录是dist_electron
目录,所以这个目录我前面做了重定向,将其定向到preload.js中。正式环境应该是不能用的,具体正式环境要怎么解决,目前我也没有搞清楚。
最终解决方案
上面衍生问题解决方案中,每次都用脚本注入的方式毕竟不方便,也不是很好使用。所以可以用如下解决方案:
不使用require关键字,而使用window.require("XXXX")
# 原来的代码
const { remote } = require('electron');
# 修改后的代码
const { remote } window.require('electron');
TypeError: fs.existsSync is not a function | import { ipcRenderer } from 'electron'
Uncaught TypeError: fs.existsSync is not a function错误
create-react-app和electron报错fs.existsSync is not a function
Electron报Uncaught ReferenceError: require is not defined