Electron使用指南 - [09] 环境搭建

174 阅读1分钟

1、搭建 Electron 环境

在你认为合适的目录下 创建 readit-vue 目录,在终端命令行里输入命令:

cd 你认为合适的目录/readit-vue
npm init -y
npm install electron@latest -D

2、创建 main.js 文件

在项目根目录下创建 main.js 文件:

// /main.js

// Modules
const {app, BrowserWindow} = require('electron')
const windowStateKeeper = require('electron-window-state')

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

// Create a new BrowserWindow when `app` is ready
function createWindow () {

  // Win state keeper
  let state = windowStateKeeper({
    defaultWidth: 500, defaultHeight: 650
  })

  mainWindow = new BrowserWindow({
    x: state.x, 
    y: state.y,
    width: state.width, 
    height: state.height,
    minWidth: 350, 
    maxWidth: 650, 
    minHeight: 300,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // Load local vue server into the new BrowserWindow
  mainWindow.loadURL('http://localhost:8080')

  // Manage new window state
  state.manage(mainWindow)

  // Open DevTools - Remove for PRODUCTION!
  mainWindow.webContents.openDevTools();

  // Listen for window being closed
  mainWindow.on('closed',  () => {
    mainWindow = null
  })
}

// Electron `app` is ready
app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow
app.on('activate', () => {
  if (mainWindow === null) createWindow()
})

3、搭建 Vue 环境, 启动 Vue 服务

在命令行里输入:

vue create vue-renderer
cd vue-renderer
yarn serve

4、配置 package.json npm 脚本

// /package.json
{
  // ...
  "scripts": {
    "start": "nodemon --exec 'electron .'"
  }
}

5、启动应用

npm start