上一篇文章我們講了如何在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,dist\electron文件夾中會編譯出worker.html和worker.js。分別打開index.html和worker.html,可以看到它們的區別如下:
於是,worker.js能夠被vue管理起來了,並且在worker.js中也能夠使用package中的第三方庫了。
如果希望執行npm run dev來自動編譯worker,只需要在package.json中增加對worker的打包命令即可。