electron-1
2020-07-03 本文已影响0人
王国的荣耀
electron 开始吧
var electron = require("electron");
var app = electron.app;
var BrowserWindow = electron.BrowserWindow;
var win = null;
app.on("ready", function () {
win = new BrowserWindow({
webPreferences: { nodeIntegration: true },
});
win.loadFile("index.html");
win.on("closed", function () {
win = null;
});
});
app.on("window-all-closed", function () {
app.quit();
});
解决 Electron 出现 Uncaught ReferenceError: require is not defined 的问题
const window = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
})
Electron主进程和渲染进程
主进程负责完成监听应用程序的生命周期事件、启动第一个窗口、加载 index.html页面、应用程序关闭后回收资源、退出程序等工作。
渲染进程负责完成渲染界面、接 收用户输入、响应用户的交互等工作。
查看当前配置
eletron-first npm config get
; cli configs
metrics-registry = "https://registry.npm.taobao.org/"
scope = ""
user-agent = "npm/6.14.4 node/v12.17.0 darwin x64"
; userconfig /Users/kingshine/.npmrc
home = "https://npm.taobao.org"
registry = "https://registry.npm.taobao.org/"
; globalconfig /usr/local/etc/npmrc
disturl = "https://npm.taobao.org/dist"
registry = "https://registry.npm.taobao.org/"
; node bin location = /usr/local/bin/node
; cwd = /Users/kingshine/Desktop/eletron-first
; HOME = /Users/kingshine
; "npm config ls -l" to show all defaults.
Electorn 实战
https://github.com/electron-in-action
调试主进程
构建 build任务
task.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"problemMatcher": [],
"label": "npm: start",
"detail": "electron .",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
launch.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"problemMatcher": [],
"label": "npm: start",
"detail": "electron .",
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
对话框
//main.js
exports.getFileFromUser = () => {
dialog
.showOpenDialog(mainWindow, {
properties: ["openFile", "openDirectory"],
filters: [
{ name: "Markdown Files", extensions: ["md", "markdown"] },
{ name: "Text Files", extensions: ["txt"] },
],
})
.then((result) => {
console.log(result.canceled);
console.log(result.filePaths[0]);
openFile(result.filePaths[0]);
})
.catch((err) => {
console.log(err);
});
};
const openFile = (file) => {
const content = fs.readFileSync(file).toString();
console.log(content);
mainWindow.webContents.send("file-opened", file, content); // B
};
//renderer.js
const { remote, ipcRenderer } = require('electron');
ipcRenderer.on('file-opened', (event, file, content) => {
markdownView.value = content;
renderMarkdownToHtml(content);
});