vuerequire不存在页面_vue+electron中的app.vue中使用require,导致页面空白

代码

My APP

let { remote } = require('electron');

export default {

methods: {

close() {

remote.getCurrentWindow().close();

},

minisize() {

remote.getCurrentWindow().minimize();

},

restore() {

remote.getCurrentWindow().restore();

},

maxsize() {

remote.getCurrentWindow().maximize();

},

data() {

return {

isMaxSize: false

};

},

mounted() {

let win = remote.getCurrentWindow();

win.on('maximize', () => {

this.isMaxSize = true;

this.setState();

});

win.on('unmaximize', () => {

this.isMaxSize = false;

this.setState();

});

},

}

};

问题描述

运行Electron+Vue项目后,应用显示空白,并报如下错误:

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中。正式环境应该是不能用的,具体正式环境要怎么解决,目前我也没有搞清楚。

参考资料

你可能感兴趣的:(vuerequire不存在页面)