electron打包vue-cli項目爲桌面程序(三):開發環境使用electron開發桌面應用

一:引入electron

cnpm install electron --save-dev 在開發環境使用electron

二:build文件夾下增加electron-preload.js文件,內容可以爲空。

主要用來在創建桌面窗口前定義一些window全局變量。可根據項目自行定義。如:window.isElectron = true 在項目中進行判斷是否爲桌面程序打開,可以調用electron的一些api

三:build文件夾下增加electron_dev.js文件

內容爲:

// Modules to control application life and create native browser window
const {
  app,
  BrowserWindow,
  Menu
} = require('electron') // 引入electron
const path = require('path') // 引入文件路徑處理插件

// 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 // 定義桌面應用窗口

// 創建桌面應用窗口
function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 1280, // 初始寬度
    height: 800, // 初始高度
    minWidth: 1280, // 最小寬度
    minHeight: 800, // 最小高度
    webPreferences: {
      nodeIntegration: true, // 可以使用nodejs原生api
      preload: path.join(__dirname, 'electron-preload.js') // 創建桌面前引用的js文件,可以用來定義一些window全局變量
    }
  })

  // and load the index.html of the app.
  // mainWindow.loadFile('index.html')
  mainWindow.loadFile(path.join(__dirname, '../dist/index.html')) // 桌面應用打開的html文件

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

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

四:修改config/index.js文件 build對象參數assetsPublicPath的值爲‘./’,改成相對路徑,否則打包後桌面程序請求不到資源

五:package.json文件中增加運行腳本

"electron_dev":"electron ./build/electron_dev.js"

然後執行npm run electron_dev

顯示如下:

下一章講解使用electron-packager打包

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章