Electron-vue实现后台多进程(二)

上一篇文章我们讲了如何在electron-vue中实现后台进程并与渲染进程进行通讯。但是添加的进程代码脱离于electron之外,如果我们想在worker中使用package.json中引入的第三方库,该怎么做呢?

首先,我们要知道package.json文件中的第三方库是怎么被引入到vue之中的。

package.json文件是webpack的一个重要组成部分,而webpack则是大名鼎鼎的js模块打包组织工具。electron-vue框架已经引入了webpack对vue代码的管理,我们要做的就是,将我们的后台进程代码添加到webpack之中。

为了结构更清晰,这里将worker.html改为了worker.ejs,并建立了一个与renderer同级的目录worker,里头存放worker的js脚本。结构如下:

|-- src

    |-- worker.ejs

    |-- index.ejs

    |-- renderer

    |-- main

    |-- worker

         |-- worker.js

webpack除了拥有一份package.json之外,还有一组以webpack开头的config.js文件。在electron-vue框架中,这些文件存放的位置如下:

|-- .electron-vue

    |-- webpack.main.config.js

    |-- webpack.renderer.config.js

    |-- webpack.web.config.js

我们主要要做的是修改这几个文件。

在webpack.renderer.config.js中,添加一个称之为worker的入口:

  entry: {
    renderer: path.join(__dirname, '../src/renderer/main.js'),
    worker: path.join(__dirname, '../src/worker/worker.js')
  },

接下来修改plugins部分,分离打包。对原来的index部分,增加如下红色所示

new HtmlWebpackPlugin({
      filename: 'index.html',
      template: path.resolve(__dirname, '../src/index.ejs'),
      chunks: ['renderer', 'vendor'],
      minify: {
        collapseWhitespace: true,
        removeAttributeQuotes: true,
        removeComments: true
      },
...

然后添加一个新的HtmlWebpackPlugin,类似上面的代码,红色部分表示只将worker这部分打包进去:

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

webpack.web.config.js文件中也是类似的操作。

然后,对于worker.ejs中的内容,只要把index.ejs完全复制进来就可以了。

运行npm run build,distelectron文件夹中会编译出worker.html和worker.js。分别打开index.html和worker.html,可以看到它们的区别如下:

于是,worker.js能够被vue管理起来了,并且在worker.js中也能够使用package中的第三方库了。

原文地址:https://www.cnblogs.com/webbery/p/12785108.html