【Electron】使用 electron-vue 高效构建桌面应用程序

electron 是一个不错的开发桌面应用程序的好工具。前面两篇文章已经基本上展现了它的魔力。纵使功能再强大,也需要一件趁手的武器来提高开发的效率。本身 electron 是借助 HTML、JS、CSS 强大的表现力,再在 Chromium 引擎上实现了一系列的界面渲染以及底层系统 API 的调用。
目前国内使用 vue 作为前端开发套件的人非常多。如果能把 vue 与 electron 结合起来开发桌面应用将事半功倍。于是就有人基于这种的构想设计出了 electron-vue 套件。能让更多的人更方便快捷开发出桌面应用。

一、安装 vue-cli

vue-cli
提供了快捷的工具创建 electron-vue 项目。

> npm install -g vue-cli

二、创建 electron-vue 项目

> vue init simulatedgreg/electron-vue my-project

my-project
的项目名称。您可以指定一个自己喜欢的项目名称。

二、安装依赖并启动

因为后面会用到 yarn
工具。所以,我们先安装它。

> npm install -g yarn

然后,再安装依赖:

> cd my-project
> yarn
> yarn run dev

windows
系统执行 yarn
的时候可能会提示:“因为在此系统上禁止运行脚本”。这是因为 windows
系统限制所致。只需要打开即可。

打开方式详见:《 Visual Studio Code :因为在此系统上禁止运行脚本》

三、解决错误

由于版本原因,可能会出现 ReferenceError: process is not defined
这样的错误。解决办法也很简单:

1)webpack.web.config.js 修改:

在项目根目录下的 .electron-vue
目录下有一个 webpack.web.config.js
文件,找到大概如下这个位置:

......
new HtmlWebpackPlugin({
......
})
......

将该段代码更改为如下:

new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../src/index.ejs'),
      templateParameters(compilation, assets, options) {
        return {
          compilation: compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options: options
          },
          process,
        };
      },
      minify: {
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true
      },
      nodeModules: false
})

2) webpack.randerer.config.js 修改:

1)
一样找到同样的位置,只不过修改的代码却不相同。如下为修改后的结果:

new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../src/index.ejs'),
      templateParameters(compilation, assets, options) {
        return {
          compilation: compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options: options
          },
          process,
        };
      },
      minify: {
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true
      },
      nodeModules: process.env.NODE_ENV !== 'production'
        ? path.resolve(__dirname, '../node_modules')
        : false
})

博主从网络上找的资料以为是两个文件改成一样,导致一直报错。一直不知道问题出在哪。后来仔细对比了修改前后的差异。才发现是这里有差别。
记录自己奋斗点滴。告诉自己依旧是一个 coder 战士。