当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 如何将一个现有的Vue网页项目封装成electron桌面应用

如何将一个现有的Vue网页项目封装成electron桌面应用

2020年07月24日  | 移动技术网IT编程  | 我要评论

需求缘由

开发了很久的网页项目,领导突然想变成桌面应用,又要重写代码?no,no,no。不可能的。重写代码吃力不讨好,浪费时间,浪费精力。那么我们该怎么办呢?
幸好,electron是如此神奇,它提供了一种能让你将任何前端代码的网站页面封装成桌面应用。无论是vue,react 还是 angular等现有的框架都能实现。

基础

学习该内容需要基本的 javascript 语法基础,以及 node.js 基础。

步骤

1,安装electron依赖包(局部安装,只安装开发依赖)
npm install electron --save-dev

2,package.json 同级位置创建文件 electron.js

electron.js 文件内容:

// 主进程
// Modules to control application life and create native browser window
const {app, protocol, Menu, BrowserWindow } = require('electron')
const path = require('path')
const { readFile } = require ('fs')
const { URL } =  require ('url')

// 处理文件打包之后的访问路径为 app的相对路径,
function createProtocol(scheme) {
  protocol.registerBufferProtocol(
    scheme,
    (request, respond) => {
      let pathName = new URL(request.url).pathname
      pathName = decodeURI(pathName) // Needed in case URL contains spaces

      readFile(path.join(__dirname, pathName), (error, data) => {
        if (error) {
          console.error(`Failed to read ${pathName} on ${scheme} protocol`, error)
        }
        const extension = path.extname(pathName).toLowerCase()
        let mimeType = ''

        if (extension === '.js') {
          mimeType = 'text/javascript'
        } else if (extension === '.html') {
          mimeType = 'text/html'
        } else if (extension === '.css') {
          mimeType = 'text/css'
        } else if (extension === '.svg' || extension === '.svgz') {
          mimeType = 'image/svg+xml'
        } else if (extension === '.json') {
          mimeType = 'application/json'
        }
        respond({ mimeType, data })
      })
    },
    error => {
      if (error) {
        console.error(`Failed to register ${scheme} protocol`, error)
      }
    }
  )
}
// 防止 localStorage 不可访问
protocol.registerSchemesAsPrivileged([{
  scheme: 'app',
  privileges: {
    secure: true,
    standard: true
  }
}])

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
let template = []  //顶部菜单模板
function createWindow () {
  // Create the browser window. 桌面应用的初始宽度、高度
  mainWindow = new BrowserWindow({
    width: 1600,
    height: 1000,
    
  })

  // and load the  of the app.
  createProtocol('app')  // 创建一个应用,访问路径的初始化
  mainWindow.loadURL('app://./')  // 入口文件, 窗口指向  文件作为首页,这里可以是vue,react,angular 的打包之后的dist目录内部的文件。

  //   Open the DevTools.
  //   mainWindow.webContents.openDevTools()
  let menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu) // 重新设置桌面应用的顶部菜单
  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// 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.on('ready', createWindow)

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

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 (mainWindow === null) createWindow()
})

// 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.

3,在package.json文件中增加指令,用来启动Electron桌面应用

“scripts”: {
“dev”: “vue-cli-service serve”,
“build”: “vue-cli-service build”,
“electron-dev”: “vue-cli-service build && electron electron.js”, ------新增
“electron-build”: “electron-packager ./dist/ --arch=x64 --icon=logo.ico --overwrite” ------ 新增,打包成.exe 文件使用
},
备注:注意添加文件 logo.ico 到 package.json 的同级位置。
这里需要灵活变化:
1,vue-cli-service build 是打包成dist文件的命令,具体项目的打包命令具体替换,本项目使用了vue-cli脚手架,故命令如此。
2,./dist/ 是指生成的桌面应用是在dist文件内部的基础上打包的,因此要看你的文件在哪里,一般build之后都有一个文件。

4,在关于webpack的基础配置文件里的module.exports 内部添加一条数据 publicPath: ‘./’,
这里是为了让build之后的文件引用相对路径。

5,将所有的api 请求的前面都加上对应的网站域名。
这里最好有一个公用的函数,一般都是在axios 的 baseURL参数里面。

6,先执行 npm run electron_dev,可以运行开发中的electron桌面应用。

接下来就是怎么打包出桌面应用了,这里用的是打包工具electron-packager ,当然也可以使用别的工具。

7,安装 electron-packager
npm install electron-packager --save-dev

8,复制 package.json 到dist文件里,新增一条数据 “main”: “electron.js”,

9,复制 electron.js 到dist文件里,

10,执行 npm run electron_build ,便会生成安装包文件 vue-antd-pro-win32-x64 , 打开里面的 .exe 文件即可

总结

总体来说,代码不多,步骤也不多,但具体项目又可能遇到各种不可预测的问题,仍然需要具体问题具体分析。

参考内容

https://www.cnblogs.com/liulun/p/12984456.html

本文地址:https://blog.csdn.net/Aglaia_web/article/details/107543945

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网