前两天看了一下使用 Electron 开发应用程序,今天说说所怎样集成 Electron 和 Webpack2 来打包应用程序。
这里准备做个小的演示程序,首先安装一些这个演示程序需要看的第三方库
$ npm install --save-dev electron
$ npm install --save-dev electron-packager
$ npm install --save-dev webpack
$ npm install --save-dev webpack-dev-server
$ npm install --save-dev webpack-target-electron-renderer
$ npm install --save-dev is-electron-renderer
$ npm install --save-dev css-loader
$ npm install --save-dev style-loader
$ npm install --save-dev extract-text-webpack-plugin
注:这里使用的webpack是2.5.1版本
这个演示程序包含的文件结构如下所示:
myapp
|-- main.js
|-- package.json
|-- src
| |-- index.html
| `-- index.js
`-- webpack.config.js
{
"name": "myapp",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"electron": "webpack && electron .",
"packager": "webpack && electron-packager . --platform=linux --electron-version=1.6.6 --overwrite"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.28.1",
"electron": "^1.6.7",
"electron-packager": "^8.7.0",
"extract-text-webpack-plugin": "^2.1.0",
"is-electron-renderer": "^2.0.1",
"style-loader": "^0.17.0",
"webpack": "^2.5.1",
"webpack-dev-server": "^2.4.5",
"webpack-target-electron-renderer": "^0.4.0"
}
}
/* eslint strict: 0 */
'use strict';
const path = require('path');
const webpack = require('webpack');
module.exports ={
target: 'electron-renderer',
entry: [
'./src/index',
],
output: {
path: path.join(__dirname, 'build'),
publicPath: path.join(__dirname, 'src'),
filename: 'bundle.js',
},
module: {
rules: []
},
};
Electron App 的入口 js 文件,启动一个窗口并加载 src/index.html 文件。
/* eslint strict: 0 */
'use strict';
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('ready', () => {
mainWindow = new BrowserWindow({ width: 1024, height: 768 });
mainWindow.loadURL(`file://${__dirname}/src/index.html`);
mainWindow.webContents.openDevTools();
mainWindow.on('closed', () => {
mainWindow = null;
});
})
webpack 入口文件,这里仅仅打印当前应用是否是运行在 electron 中。
console.log('running in electron: ', require('is-electron-renderer'));
测试的 html 文件,其中使用了 webpack 预编译好的 bundle.js 文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<body>
<script src="../build/bundle.js"></script>
<ul>
<li>Node: <script>document.write(process.versions.node)</script></li>
<li>Chrome: <script>document.write(process.versions.chrome)</script></li>
<li>Electron: <script>document.write(process.versions.electron)</script></li>
</ul>
</body>
</html>