本節咱們學習如何在 Electron
中使用 Node
原生模塊。node
Electron
支持原生的 Node
模塊,但因爲和官方的 Node
相比,Electron
有可能使用一個和咱們系統上所安裝的 Node
不一樣的 V8
引擎,因此使用的模塊須要從新編譯才能使用。若是咱們想編譯原生模塊,則須要手動設置 Electron
的 headers
的位置。shell
有三種安裝原生模塊的方法,分別是 :npm
Electron
安裝並從新編譯模塊。npm
安裝原生模塊。Electron
手動編譯。最簡單的方式就是經過 electron-rebuild
包爲 Electron
重建模塊,該模塊能夠自動肯定 Electron
的版本,並處理下載 headers
、爲應用程序重建本機模塊等步驟。windows
例如要經過 electron-rebuild
來重建模塊,首先須要安裝 electron-rebuild
:緩存
npm install --save-dev electron-rebuild
每次運行 npm install
時,也會同時運行下面這條命令:bash
./node_modules/.bin/electron-rebuild
在 windows
下若是上述命令遇到了問題,能夠嘗試執行以下命令:架構
.\node_modules\.bin\electron-rebuild.cmd
咱們還能夠經過 npm
來直接安裝原生模塊。大部分步驟和安裝普通模塊時同樣,可是須要本身設置一些系統環境變量。electron
例如要安裝全部 Electron
的依賴:學習
# Electron的版本 export npm_config_target=1.2.3 # Electron的目標架構 export npm_config_arch=x64 export npm_config_target_arch=x64 # 下載Electron的headers export npm_config_disturl=https://electronjs.org/headers # 告訴node-pre-gyp咱們是在爲Electron生成模塊 export npm_config_runtime=electron # 告訴node-pre-gyp從源代碼構建模塊 export npm_config_build_from_source=true # 安裝全部依賴,並緩存到 ~/.electron-gyp HOME=~/.electron-gyp npm install
原生模塊的開發人員若是想要在 Electron
中進行測試,可能要手動編譯 Electron
模塊。可使用 node-gyp
來直接編譯。測試
例如咱們要告訴 node-gyp
去哪下載 Electron
的 headers
,以及下載什麼版本:
$ cd /path-to-module/ $ HOME=~/.electron-gyp node-gyp rebuild --target=0.29.1 --arch=x64 --dist-url=https://atom.io/download/atom-shell
HOME=~/.electron-gyp
:設置去哪找開發時的 headers
。--target=0.29.1
:設置了 Electron
的版本。--dist-url=...
:設置了 Electron
的 headers
的下載地址。--arch=x64
:設置了該模塊爲適配 64 位操做系統而編譯。