接上一篇,分清楚了两种模块的规范,那么怎么解决两种规范的不同呢,似乎可以通过配置babel来实现,于是我在babel.config.js中尝试了很多办法,都没有收效,归根结底是还没有搞清楚vue和electron之间是如何各自适用这些规范的。
按照某种说法,最新的vue是遵循ES6,而electron或者说node模块是CommonJs,但是,在项目中,npm install进来的模块都放在node_modules中,怎么区分呢,如果不是babel.config.js来负责,那就应该是electron相关的,于是我找到了electronBuilder这个配置。
在vue.config.js(如果没有则在项目根目录新建)中:
module.exports = {
configureWebpack: {
devtool: "source-map"
},
pluginOptions: {
electronBuilder: {
// List native deps here if they don't work
externals: ["escpos", "escpos-usb"]
// If you are using Yarn Workspaces, you may have multiple node_modules folders
// List them all here so that VCP Electron Builder can find them
}
}
// chainWebpack: config => {
// config.module
// .rule("js")
// .test(/\.jsx?$/)
// .exclude.clear()
// .end()
// .include.add(function() {
// return ["./node_modules/escpos", "./node_modules/escpos-usb", "src"];
// })
// .end();
// }
};
这个发现得益于https://medium.com/@nyorikakar/printing-with-vue-electron-and-node-f52a730e63e7这篇文章,而且我还在后面的评论中发现了https://github.com/song940/node-escpos/issues/297,最终靠这些信息搞清楚了逻辑。
(1)对于用于node的模块,需要在vue.config.js的externals那里列出,这样,vue就不会让babel啥的那些loader去处理了。
(2)负责和node打交道的代码要放在background.js中,这在前面第二个连接中可以看到,而且最关键的是在vue的代码因为是通过BrowserWindow加载的,在其初始化是webPreferences中的nodeIntegration这个属性需要配置为true,const { ipcRenderer } = window.require(“electron”);才能用。而且,这个true如果是放在.env中不能直接给process.env.ELECTRON_NODE_INTEGRATION=true,那样,调到的是字符串,不是布尔值,会出现下面的报错:
Uncaught TypeError: window.require is not a function
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.vue:22)
at __webpack_require__ (bootstrap:853)
at fn (bootstrap:150)
at Module../src/App.vue?vue&type=script&lang=js& (App.vue?c53a:1)
at __webpack_require__ (bootstrap:853)
at fn (bootstrap:150)
at Module../src/App.vue (App.vue:1)
at __webpack_require__ (bootstrap:853)
at fn (bootstrap:150)
at Module../src/main.js (HelloWorld.vue?adfd:1)
发表回复