Vue3.x & Ant-Design-VueVue

Electron + vue3 + vite 整合

2020-08-17  本文已影响0人  野鸡没名

毕竟 ****尤大出品,必是精品**** 定律嘛!

800x600.png

准备材料

目录结构

.
├─dist                    打包后的文件夹
├─screenshot
├─script
│  ├─build.js             主进程构建文件
│  └─rollup.config.js     主进程构建配置
└─src
    ├─main
    │  └─index.ts         主进程入口文件
    └─render
        ├─assets
        ├─components
        ├─dist            vue 打包后目录
        │  _assets
        ├─public
        ├─App.vue
        ├─index.css
        ├─index.html
        └─main.js         渲染进程入口文件
└─.env                    配置文件

主进程构建配置

script/rollup.config.js

const path = require('path');
const { nodeResolve } = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const typescript = require('@rollup/plugin-typescript');

module.exports = (env = 'production') => {
  return {
    input: path.join(__dirname, '../src/main/index.ts'), // 入口文件
    output: {
      file: path.join(__dirname, '../src/main/_.js'), // 输出目标
      format: 'cjs', // CommonJs 格式
      name: 'ElectronMainBundle', // 模块名称(可选)
      sourcemap: true,
    },
    plugins: [
      nodeResolve({ jsnext: true, preferBuiltins: true, browser: true }), // 支持引入 node_modules 模块
      commonjs(), // 支持 CommonJs 规范
      typescript(), // 支持 TypeScript
    ],
    external: [
      // 告诉 rollup 碰到下面模块时候不要去打包
      'fs',
      'path',
      'http',
      'https',
      'child_process',
      'os',
      'electron',
    ],
  }
};

主进程构建脚本

script/build.js

/**
 * electron 打包
 */
const path = require('path');
const rollup = require('rollup');
const argv = require('minimist')(process.argv.slice(2));
const chalk = require('chalk');
const ora = require('ora');
const waitOn = require('wait-on');
const electron = require('electron-connect').server.create({ stopOnClose: true }); // 表示要操作主进程端(对应的还是渲染进程端;渲染进程用的 vite 热更新)
require('dotenv').config({ path: path.join(__dirname, '../.env') }); // 解析项目根目录下的 .env 文件
const options = require('./rollup.config'); // 引入 rollup 配置

const opt = options(argv.env);
const TAG = '[script/build.js]';
const spinner = ora(`${TAG} Electron build...`);

if (argv.watch) { // 开发模式 (命令行传入 --watch 标识)
  waitOn({
    resources: [`http://localhost:${process.env.PORT}`], // 等待 vite 服务器启动,然后拉起 electron
    log: false,
  }, err => {
    if (err) {
      console.log(err);
      process.exit(1);
    }

    // once here, all resources are available
    const watcher = rollup.watch(opt);
    watcher.on('change', filename => {
      const log = chalk.green(`change -- ${filename}`);
      console.log(TAG, log);
    });
    watcher.on('event', ev => {
      if (ev.code === 'END') {
        // init-未启动、started-第一次启动、restarted-重新启动
        electron.electronState === 'init' ? electron.start() : electron.restart();
      }
    });
  });
} else { // 构建模式
  spinner.start();
  rollup.rollup(opt)
    .then(build => {
      spinner.stop();
      console.log(TAG, chalk.green('Electron build successed.'));
      build.write(opt.output);
    })
    .catch(error => {
      spinner.stop();
      console.log(`\n${TAG} ${chalk.red('构建报错')}\n`, error, '\n');
    });
}

渲染进程 vite 配置

vite.config.ts

/**
 * 参考链接: https://github.com/vitejs/vite/blob/master/src/node/config.ts
 */
import { join } from 'path'
import { UserConfig } from 'vite'
import dotenv from 'dotenv'

dotenv.config({ path: join(__dirname, '.env') })

const config: UserConfig = {
  // vite 项目编译、启动的根目录
  // 默认指向项目跟目录,我们把 vue(渲染进程) 代码全部搬到 src/render 下
  root: join(__dirname, 'src/render'),
  // 通过 .env 配置端口,能够让 electron 加载到正确的地址
  port: +process.env.PORT,
  // 打包后的 vue 项目引入 js、css、favicon 等资源路径
  base: './',
}

export default config

启动脚本配置

{
  "main": "src/main/_.js",
  "scripts": {
    "dev": "npm run dev:all",
    "dev:all": "concurrently -n=vue,ele -c=green,blue \"npm run dev:vue\" \"npm run dev:ele\"",
    "dev:vue": "vite",
    "dev:ele": "node script/build --env=development --watch",
    "build:vue": "vite build",
    "build:ele": "node script/build --env=production",
    "build": "npm run build:vue && npm run build:ele && electron-builder"
  }
}

启动一下试试

$ yarn dev  

yarn run v1.22.4                                                                                    
$ npm run dev:all                                                                                   
                                                                                                    
> electron-vue@0.0.1 dev:all D:\github\electron-vue-vite                                            
> concurrently -n=vue,ele -c=green,blue "npm run dev:vue" "npm run dev:ele"                         
                                                                                                    
[ele]                                                                                               
[ele] > electron-vue@0.0.1 dev:ele D:\github\electron-vue-vite                                      
[ele] > node script/build --env=development --watch                                                 
[ele]                                                                                               
[vue]                                                                                               
[vue] > electron-vue@0.0.1 dev:vue D:\github\electron-vue-vite                                      
[vue] > vite                                                                                        
[vue]                                                                                               
[vue] vite v1.0.0-rc.4                                                                              
[vue]                                                                                               
[vue]   Dev server running at:                                                                      
[vue]   > Network:  http://192.168.1.9:3344/                                                        
[vue]   > Network:  http://192.168.119.1:3344/                                                      
[vue]   > Network:  http://10.0.60.32:3344/                                                         
[vue]   > Local:    http://localhost:3344/                                                          
[vue]                                                                                               
[ele] [2020-08-17T08:57:11.850Z] [electron-connect] [server] started electron process: 1488         
[ele] [2020-08-17T08:57:11.851Z] [electron-connect] [server] server created and listening on 30080  
[ele]                                                                                              

完整代码 https://github.com/caoxiemeihao/electron-vue-vite

尾巴

上一篇 下一篇

猜你喜欢

热点阅读