Electron初体验Log.

Electron 可以把 web 开发的应用打包成桌面软件,开始具体实战:

首先从github拉取项目
git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
cnpm install(或者yarn npm)

运行项目
cnpm run start

项目运行起来以后会自动打开一个客户端界面,默认的配置文件是根目录下的 package.json 和 main.js

默认是挂载了一个 index.html 的文件,加载方法是 loadFile(详见 main.js 中的配置)

main.js 配置:

//文件默认配置:
mainWindow.loadFile('index.html');

// 如果要嵌入页面可以直接把这行配置改成下面,运行起来后 会直接跳转到百度首页
mainWindow.loadURL('https://www.baidu.com');

//另外可以配置默认打开时最大化打开,不是全屏,保留状态栏
mainWindow.maximize();

// PS:配置上面最大化打开 需要同时允许一下↓↓↓
const mainWindow = new BrowserWindow({
  title: "标题",
  maximizable: true,
})

上述嵌页面的方法最简单,最方便,但是有一点实现不了的需求;试过很多种方法,顶部的 title 是根据页面去加载的,而不可以自己去设置。如果是用默认配置 loadFile 的方法,title 是根据 index.html 中的 title 加载的。

实现 index.html 嵌页也很简单,需要使用 Electron 的 webview 标签载入即可。

实现后的效果 ↓↓↓(是的,大家都看到了 👁,默认高度是有问题的,看到最后会有解决方案)

图片[1]-Electron初体验Log.-极客屿 Geek Island.

虽然是嵌入百度的页面 但是名字是自定义的。

  • 第一步:在 main.js 中打开 webview 标签;
 webPreferences: {
  webviewTag: true
}
  • 第二步:修改index.html
<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8">

    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->

    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">

    <link href="./styles.css" rel="stylesheet">

    <title>前端劝退师的炼丹炉</title>

  </head>

  <body style="margin:0 ;padding:0;">

    <webview id="wb" src="https://www.baidu.com" /> //这里的src里填入自己想嵌入的地址

    <script src="./renderer.js"></script>

  </body>

</html>
  • 第三步:修改 renderer.js
  • 做这步的目的是,使 webview 全屏,不然只会展示默认高度;
// 初始化给id复制默认的高度
document.getElementById('wb').style.height = document.documentElement.clientHeight + 'px';

// 监听窗口尺寸变化,重新高度赋值
window.onresize = function () {
  document.getElementById('wb').style.height = document.documentElement.clientHeight + 'px';
}

最终的效果:

图片[2]-Electron初体验Log.-极客屿 Geek Island.

到此套壳桌面软件已经结束了,下面是打包内容:

当调试完 确定没问题了,下面就该开始打包了,打包需要安装新的组件

cnpm install electron-packager --save-dev

electron-packager 是打包插件,可以为 linux、mac、windows 等平台打包应用。

安装完上面依赖后,修改 package.json 文件,增加打包操作:

"scripts": {
  "start": "electron .",
    "electron_build": "electron-packager ./ 你的app名字 --platform=darwin --arch=x64 --icon=icon/icon.icns --overwrite"
}

上述参数解释:

  • 你的 app 名字:顾名思义
  • –platform=darwin 打包平台,输出的哪个端的桌面应用文件
  • 选项有:
    • linux
      • linux 客户端
    • win32
      • windows 端(常用)
    • darwin
      • mac 端普通版(常用)
    • mas
      • mac 端,appstore 版
    • all
      • 全部生成
    • –arch=x64 打包版本
      • 可选项:ia32、x64、armv7l、all
    • –icon 打包图标
      • 这里要注意的是,最佳大小为 256*256
      • 打包 windows 应用需要用到的后缀是.ico
      • 打包 mac 应用需要用到的后缀是.icns(我用的是 mac 打包,就因为后缀问题 排坑一小时才发现这个问题,市面上的教程大多是 windows 的)

最后执行打包命令:

cnpm run electron_build

会在根目录下生成一个文件夹,打开就能找到生成的可执行文件,over!

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容