很简单的代码:
main.js:
const { app, BrowserWindow } = require("electron")
const path = require('path')
const createWindow = () => {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
contextIsolation: false,
preload: path.join(__dirname, 'preload.js'),
}
})
//引用本地地址
win.loadFile('index.html')
//打开开发者工具
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)
preload:
const path = require('path')
console.log(__dirname)
const fs = require('fs')
fs.writeFile("I:/electron/aaa.txt", 'abc', () => {
console.log("done.")
})
index.html
但运行一直出下面的错误:
1:node:electron/js2c/sandbox_bundle:93 Unable to load preload script: I:\electron\preload.js
2:node:electron/js2c/sandbox_bundle:93 Error: module not found: path
首页可以排除node安装或环境的问题,这块肯定没问题。
光看错误信息的话:
preload.js
里使用了path
模组,浏览器里不存在,于是运行失败,导致加载preload.js
失败。