electron环境配置
创建vue项目
添加vue插件:vue add electron-builder
修改background.ts
安装typescript和ts-loader
Npm install typescript
Npm install ts-loader@8.2.0
或
Npm install-g typescript
Npm install-g ts-loader@8.2.0
这里要注意,这两个要么都全局安装,要么都局部安装,不可以混合,不然会提示找不到typescript模块
另外ts-loader不要安装最新的,版本太高会提示找不到一些方法,就安装这个版本就可以
关闭火绒
// Vue.condfig.js
// 上下文通信
const { defineConfig } = require('@vue/cli-service')
// const { machineId, machineIdSync } = require('node-machine-id')
// console.log(JSON.stringify(machineIdSync({ original: true })))
module.exports = defineConfig({
transpileDependencies: true,
pluginOptions: {
electronBuilder: {
preload: 'src/preload.js'
}
}
})
// Background.ts
const path = require('path')
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: (process.env
.ELECTRON_NODE_INTEGRATION as unknown) as boolean,
contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
preload: path.join(__dirname, 'preload.js')
}
Background.ts同级目录新建preload.js
参考:
上下文隔离 | Electron (electronjs.org)
Security | Vue CLI Plugin Electron Builder (nklayman.github.io)
import { machineId, machineIdSync } from 'node-machine-id' // 获取设备id用的,
import { contextBridge } from 'electron'
contextBridge.exposeInMainWorld('myAPI', {
machineId: machineIdSync(true),
random: () => { return Math.random() }
})
const fff = require('node-machine-id');
参考:
上下文隔离 | Electron (electronjs.org)
nodeIntegration:true // 给渲染层 node环境,可以在渲染层调用Node.js的api
contextIsolation:false // 禁用上下文隔离,与nodeIntegration取其一
webpack跳过require
// eslint-disable-next-line no-undef
const xxx = __non_webpack_require__('xxx')