将Vue项目打包为Windows应用

醉菜鸟 2021-12-13 09:01:01

Vue安装electron依赖

npm install electron --save-dev
npm install electron-packager --save-dev

在package.json 文件添加指令

"scripts": {
    "electron-build": "electron-packager ./dist/ --platform=win32 --arch=x64 --icon=./dist/favicon.ico --overwrite"
}

运行命令

npm run build

运行之后会生成dist目录,在dist文件下面添加 package.json

{
  "name": "name",
  "version": "0.0.1",
  "license": "name",
  "author": "hk",
  "build": {
    "asar": true,
    "win": {
      "target": [
        {
          "arch": [
            "ia32"
          ],
          "target": "nsis"
        }
      ],
      "icon": "./resources/ico.ico"
    },
    "directories": {
      "output": "build"
    },
    "productName": "name",
    "extraResources": {
      "to": "../assets",
      "from": "./assets/"
    },
    "appId": "com.qq.xxxx"
  },
  "env": "online",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron .",
    "dist": "electron-builder",
    "pack": "electron-builder --dir"
  },
  "keywords": [
    "win student"
  ],
  "main": "./electron.js",
  "dependencies": {},
  "devDependencies": {},
  "description": "description"
}

在dist文件下面添加 electron.js

// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron')
const path = require('path')

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1600,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'index.html')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  createWindow()

  app.on('activate', function() {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function() {
  if (process.platform !== 'darwin') app.quit()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

运行命令

npm run electron-build
意见反馈