vue项目用electron打包成exe,并更新exe版本

1 篇文章 0 订阅

用electron-build打包

1、下载electron、electron-builder

npm install electron electron-builder -D

2、配置package.json文件

    "start": "electron .",

    "app:build": "electron-builder"

  "build": {
    "appId": "com.xx.xx",
    "productName": "后台管理系统",
    "directories": {
      "output": "dist_electron"
    },
    "extends": null,
    "asar": true,
    "publish": [
      {
        "provider": "generic",
        "url": "更新目录地址"
      }
    ],
    "nsis": {
      "oneClick": false,
      "allowElevation": true,
      "allowToChangeInstallationDirectory": true,
      "createDesktopShortcut": true,
      "createStartMenuShortcut": true,
      "shortcutName": "后台管理系统"
    },
    "dmg": {
      "contents": [
        {
          "x": 410,
          "y": 150,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 130,
          "y": 150,
          "type": "file"
        }
      ]
    },
    "mac": {
      "icon": "src/resources/icons/icon.icns"
    },
    "win": {
      "icon": "src/resources/icons/icon.ico",
      "target": [
        {
          "target": "nsis",
          "arch": [
            "ia32"
          ]
        }
      ]
    },
    "linux": {
      "icon": "src/resources/icons/icon.ico"
    }
  }

3、在根目录创建main.js文件

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

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        // titleBarStyle: 'hidden', //隐藏标题栏
        // frame: false, //无边框窗口
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false,
            // preload: path.join(__dirname, 'preload.js')
        }
    })

    // 隐藏顶部菜单
    mainWindow.setMenu(null)

    // and load the index.html of the app.
    mainWindow.loadFile('./dist/index.html')
    // mainWindow.loadURL('http://127.0.0.1:8080')
    // mainWindow.loadURL(`file://${__dirname}/dist/index.html`)

    mainWindow.maximize()
    mainWindow.show()

    // 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()
    })
})

app.on('ready', () => {
    // mainWindow = createMainWindow();
    // if (!isDevelopment) updateHandle()
})

// 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()
})

注意:

要在package.json文件添加一下代码,否则可能不能正常运行,会报错

"main": "main.js",

用electron-updater更新 

需要一个静态服务器来暴露文件,我这里用的时nodejs做了一个临时的静态服务器

1、下载electron-updater

npm install electron-updater -D

2、配置package.json文件(和build里面的appId同级)

"publish": [

      {

        "provider": "generic",

        "url":"http://localhost:3008/"

      }

    ],

3、在主进程里面添加检查更新、下载代码(为了方便,把打包代码也放了进去,但是这里没有下载进度条显示,也没有和渲染进程互动,检测到更新后下载无法显示进度)

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

const {
    autoUpdater
} = require('electron-updater')

// 强制打包状态
// Object.defineProperty(app, 'isPackaged', {
//     get() {
//         return true;
//     }
// })

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\');
}

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{
    scheme: "app",
    privileges: {
        secure: true,
        standard: true
    }
}, ]);

// 存在新版本时,默认自动下载更新
autoUpdater.autoDownload = false // 若想通过渲染进程手动触发,需要设置autoDownload为false

// autoUpdater.setFeedURL({
//     provider: 'generic',
//     url: 'http://localhost:3008/', // 打包文件存放地址
// })

function createWindow() {
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        // titleBarStyle: 'hidden', //隐藏标题栏
        // frame: false, //无边框窗口
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            webSecurity: false,
            // preload: path.join(__dirname, 'preload.js')
        }
    })

    // 隐藏顶部菜单
    mainWindow.setMenu(null)

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

    mainWindow.maximize()
    mainWindow.show()

    // 打开F12调试窗口
    // mainWindow.webContents.openDevTools()

    // 关闭窗口提示框
    mainWindow.on("close", (e) => {
        e.preventDefault();
        dialog.showMessageBox(mainWindow, {
            type: "warning",
            title: "关闭",
            message: "是否要关闭程序",
            buttons: ["yes", "no"],
        }).then((index) => {
            if (index.response === 0) {
                app.exit();
            }
        })
    })

    // =========================================检测软件更新==========================================
    autoUpdater.checkForUpdates();

    //检查更新
    autoUpdater.on('checking-for-update', () => {})

    //没有可用更新
    autoUpdater.on('update-not-available', () => {})

    //有可用更新
    autoUpdater.on('update-available', (info) => {
        // autoUpdater.downloadUpdate()
        dialog.showMessageBox({
            type: 'question',
            buttons: ['yes', 'no'],
            title: '更新提示',
            message: '是否下载最新版本?',
        }).then((res) => {
            if (res.response === 0) {
                // 开始下载
                autoUpdater.downloadUpdate()
            }
        })
    })

    // 更新出错
    autoUpdater.on('error', (err) => {
        dialog.showMessageBox({
            type: 'error',
            buttons: ['yes', 'no'],
            title: '更新提示',
            message: '更新出错!',
        })
    })

    // 下载进度
    autoUpdater.on('download-progress', (progressObj) => {
        let log_message = progressObj.percent + '% (' + progressObj.transferred + "/" + progressObj.total + ')'

        console.log('下载进度:' + log_message);
    })

    // //更新下载完成
    autoUpdater.on('update-downloaded', (info) => {
        autoUpdater.quitAndInstall();
        // mainWindow.destroy()
    })
}

// 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()
    })
})

app.on('ready', () => {})

// 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()
})

nodejs静态服务器代码(用express)

const express = require('express');
const path = require('path');
const app = express();
const cors = require('cors');

const PORT = 3008;

// 启用 CORS 中间件
app.use(cors());

// 处理跨域请求
// app.get('/user', (req, res) => {
// res.send({ name: 'John', age: 30 });
// });

// app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static('public'));

// 如果需要添加路由,可以在这里添加

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

  • 6
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值