已经打包好了的vue dist文件夹,如何用electron打包成exe桌面应用

先在项目根目录下(非dist根目录)安装electron electron-packager

npm install electron

再在项目根目录下(非dist根目录)安装electron-packager

npm install electron-packager

然后在dist文件夹下创建main.js文件,内容为

const { app, BrowserWindow, Menu } = require('electron');
const path = require('path');

function createWindow() {
  Menu.setApplicationMenu(null);

  // 浏览器窗口
  let win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false  // 禁用同源策略,仅用于开发和测试阶段,因为后台可能会报错跨域问题
    }
  });

  // 使用 file 协议加载 index.html 文件,因为不用file协议加载会没有权限
  win.loadURL(`file://${path.join(__dirname, 'index.html')}`);

  // 打开开发者工具,没问题不开也行
  win.webContents.openDevTools();

  // 监听窗口关闭事件,关闭开发者工具
  win.on('closed', () => {
    win = null;
  });
}

// 监听浏览器窗口有没有准备好
app.whenReady().then(createWindow);

// 所有窗口都被关闭后
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

再创建一个文件package.json

{
  "name": "electron-quick-start",
  "version": "1.0.0",
  "description": "A minimal Electron application",
  "main": "main.js",
  "scripts": {
  "start": "electron .",
  "package": "electron-packager . HelloWorld --platform=win32 --arch=x64 --icon=computer.ico --out=./out --asar --app-version=0.0.1 --overwrite --ignore=node_modules"
  },
  "repository": "https://github.com/electron/electron-quick-start",
  "keywords": [
  "Electron",
  "quick",
  "start",
  "tutorial",
  "demo"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
  "electron": "^9.0.0"
  },
  "dependencies": {
  "electron-packager": "^14.2.1"
  }
  }
  

在非dist文件夹(注意,是非dist文件夹,就是原本没打包的项目文件里)的package.json文件里,改一下script

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "test": "vue-cli-service build --mode test",
    "lint": "vue-cli-service lint",
    "electron_dev": "npm run build && electron main.js",
    "electron_build": "electron-packager ./dist name --platform=win32 --arch=x64 --overwrite",
  
    "dist": "electron-packager ./dist name --platform=win32 --arch=ia32 --overwrite" 
  },

最后在项目文件根目录(非dist文件夹目录)里执行electron_build,完成打包

再运行name.exe就可以了

你可能感兴趣的:(vue.js,electron,javascript,前端,webpack)