技术思绪摘录旅行笔记
Electron一个使用HTML、CSS和JavaScript开发桌面应用程序的框架。Electron可以生成在Windows、macOS和Linux上运行的应用程序,借助Electron可以把我们的web端应用直接移植到桌面端而无需再次开发,这样我们可以使用同一套代码在不同平台上运行应用,极大的缩短了开发时间。

1:安装NodeJS https://nodejs.org/zh-cn/

2:安装IDE  VsCode

3:检查Node JS和Npm是否安装好

node -v
npm -v

4、修改npm源

npm config set registry https://registry.npm.taobao.org
检测是否成功
// 配置后可通过下面方式来验证是否成功
npm config get registry
// 或
npm info express
//如果想还原npm仓库地址,只需再把地址配置成npm镜像就可以了
npm config set registry https://registry.npmjs.org/

//首先安装cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
//mac
sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

5、安装Electron

//使用cnpm进行安装,使用方法和npm相同
cnpm install -g electron
//检查是否安装成功
electron -v
也可以安装yarn,使用yarn来安装
npm install -g yarn

6、初始化项目

npm init

7、引用Electron依赖

cnpm install electron --save-dev
//全局
cnpm install electron -g

//安装代码检查
cnpm install -g eslint
//使用
eslint --init

8、项目创建完成,我们开始写代码,添加一个main.js

const { app, BrowserWindow } = require('electron')

function createWindow () {   
  // 创建浏览器窗口
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // 并且为你的应用加载index.html
  win.loadFile('index.html')

  // 打开开发者工具
  win.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // 在 macOS 上,除非用户用 Cmd + Q 确定地退出,
  // 否则绝大部分应用及其菜单栏会保持激活。
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // 在macOS上,当单击dock图标并且没有其他窗口打开时,
  // 通常在应用程序中重新创建一个窗口。
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. 也可以拆分成几个文件,然后用 require 导入。

9、添加一个index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <!-- https://electronjs.org/docs/tutorial/security#csp-meta-tag -->
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  </head>
  <body>
    <h1>Hello World!</h1>
    We are using node <script>document.write(process.versions.node)</script>,
    Chrome <script>document.write(process.versions.chrome)</script>,
    and Electron <script>document.write(process.versions.electron)</script>.
  </body>
</html>

10、运行一下,启动程序

npm start

这就是最简单的一个Electron程序,全是前端技术,下一篇介绍脚手架

CarsonIT 微信扫码关注公众号 策略、创意、技术

留下您的脚步

 

最近评论

查看更多>>

站点统计

总文章数:275 总分类数:18 总评论数:88 总浏览数:124.92万

精选推荐

阅读排行

友情打赏

请打开您的微信,扫一扫