Electron将网页打包成桌面应用

发布于 / 前端 / 10 条评论

在打包之前,你需要准备:

  1. 安装并配置好node.js(全局安装)
  2. 使用npm安装了electron(全局安装)
  3. 写好的网页

下面开始打包:

1.打开你的网页文件夹,新建main.js、package.json,并且确保有index.html(这是你的主页入口,也可以改成其他名字)

2.在package中写:

{
  "name"    : "app-name",
  "version" : "0.1.0",
  "main"    : "main.js"
}

3.在 main.js 中添加下面的内容,这个 main.js 文件就是上面 package.json 中的 “main”键 的值,所以可根据需要修改,需要注意的是这里设置的窗口大小是800X600,很有可能打包之后会出现布局错乱,所以你要改成页面显示的最佳比例

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')
 
// 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 win
 
function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({width: 800, height: 600})
 
  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))
 
  // Open the DevTools.
  // win.webContents.openDevTools()
 
  // Emitted when the window is closed.
  win.on('closed', () => {
    // 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.
    win = 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', () => {
  // 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', () => {
  // 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 (win === 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.

4.在你的网页目录打开命令窗口,输入:(安装electron)

npm install electron-packager -g

5.输入以下命令开始打包:

electron-packager . app --win --out presenterTool --arch=x64 --electron-version 1.4.14 --overwrite --ignore=node_modules

以上命令中electron-packager . (应用名) –win –out (打包生成的文件名) –arch=(系统) –electron-version (electron版本) –overwrite –ignore=node_modules

6.新手可能比较关心打包之后,还能否与后台交互的问题,其实这个问题本就不存在,因为你能在打包的文件内找到原本的那个HTML文件,而EXE窗口只是一种显示模式

7.本文大部分引自  戳我 原文中打包命令不可用,可参考上面第五步的命令

转载原创文章请注明,转载自: 锅盖君 » Electron将网页打包成桌面应用
  1. avatar

    周五了gay 又是一事无成的一周 哭唧唧 想要甜甜的面试~

    1. avatar
      @李宇童鞋丶 又是一个周二,开心不?
  2. avatar

    又是周五了 gay~ 周末好、

    1. avatar
      @李宇童鞋丶 我离职了
  3. avatar

    周二了 gay~

    1. avatar
      @李宇童鞋丶 你个孤独的老男人
  4. avatar

    周五了 gay~~

    1. avatar
      @李宇童鞋丶 你能不能换句话。。。
  5. avatar

    周五了 gay

    1. avatar
      @李宇童鞋丶 美滋滋