electron-vue开发笔记(3)多窗口多页面入口配置

6,919 阅读1分钟

准备写个系列,先把flag立上~

问题

electron-vue默认的配置是单页面应用,但是在这种情况下想实现多个窗口多页面入口,即

同时打开aWin,bWin两个窗口,
且aWin窗口展示a.html,bWin窗口展示b.html。

解决方案

1. 创建多页面

首先在renderer里创建两个Vue实例,为了方便管理,统一放到pages路径下。提出store统一管理这两个Vue实例,文件结构如图,具体代码可见文末的repo地址。

renderer多页面文件结构

2. 修改打包脚本

首先添加打包多个页面的脚本 multi-page.config.js:

const glob = require('glob');
const path = require('path');
const PAGE_PATH = path.resolve(__dirname, '../src/renderer/pages');
const HtmlWebpackPlugin = require('html-webpack-plugin');

exports.entries = function () {
  /*用于匹配 pages 下一级文件夹中的 index.js 文件 */
  var entryFiles = glob.sync(PAGE_PATH + '/*/main.js')
  var map = {}
  entryFiles.forEach((filePath) => {
    /* 下述两句代码用于取出 pages 下一级文件夹的名称 */
    var entryPath = path.dirname(filePath)
    var filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1)
    /* 生成对应的键值对 */
    map[filename] = filePath
  })
  console.log('entry: ', map)
  return map
}

exports.htmlPlugin = function () {
  let entryHtml = glob.sync(PAGE_PATH + '/*/index.ejs')
  let arr = []
  entryHtml.forEach((filePath) => {
    var entryPath = path.dirname(filePath)
    var filename = entryPath.substring(entryPath.lastIndexOf('\/') + 1)
    let conf = {
      template: filePath,
      filename: `${filename}.html`,
      chunks: [filename],
      inject: true,
      nodeModules: path.resolve(__dirname, '../node_modules'),
      templateParameters (compilation, assets, options) {
        return {
          compilation: compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options: options
          },
          process,
        };
      }
    }
    if (process.env.NODE_ENV === 'production') {
      let productionConfig = {
        minify: {
          removeComments: true,         // 移除注释
          collapseWhitespace: true,     // 删除空白符和换行符
          removeAttributeQuotes: true   // 移除属性引号 
        },
        chunksSortMode: 'dependency'    // 对引入的chunk模块进行排序
      }
      conf = { ...conf, ...productionConfig } //合并基础配置和生产环境专属配置
    }
    arr.push(new HtmlWebpackPlugin(conf))
  })
  console.log('plug: ', arr)
  return arr
}
  • 然后修改webpack.renderer.config.js文件,更新entrypoint及plugin,整体代码可见文末仓库地址。
// webpack.renderer.config.js
const { entries, htmlPlugin } = require('./muti-page.config')

let rendererConfig = {
    entry: entries,
    plugins: [
        new VueLoaderPlugin(),
        new MiniCssExtractPlugin({filename: 'styles.css'}),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin()
    ].concat(htmlPlugin()),
}

3. 新建窗口加载新页面

这里需要注意的是:在 multi-page.config.js 配置的模版名称以 page 文件夹名命名。所以新页面要加载page2.index。

const winURL = process.env.NODE_ENV === 'development'
  ? `http://localhost:9080/page2.html`
  : `file://${__dirname}/page2.html`

效果

多窗口多页面示例

Happy Ending

Github源码