原文:https://github.com/electron/electron/blob/master/docs/tutorial/using-native-node-modules.md
譯者:Lin
Electron支持native Node modules,但是因為Electron非常有可能從安裝在你系統的Node二進制文件中使用一個不同版本的V8,你必須要在編譯native modules時手動指定本地Electron頭部。
<h2 id="how-to-install-native-modules">如何安裝本地模塊</h2>
三種方法安裝native modules:
<h3 id="using-npm">使用<code>npm</code></h3>
通過設置一些環境變量,你可以直接使用npm
來安裝模塊。
一個Electron所有依賴的例子:
# Electron的版本。
export npm_config_target=1.2.3
# Electron架構,可以是ia32或者x64.
export npm_config_arch=x64。
export npm_config_target_arch=x64
# 下載Electron的頭部。
export npm_config_disturl=https://atom.io/download/electron
# 告訴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
<h3 id="installing-modules-and-rebuilding-for-electron">安裝模塊并且重新編譯Electron</h3>
你可以像其他Node項目一樣選擇安裝模塊,然后使用electron-rebuild
包重新編譯Electron的模塊。這個模塊可以得到Electron的版本并且處理手動步驟中的下載頭部和為你的應用編譯native modules。
安裝electron-rebuild
并且使用它重編譯模塊的例子:
npm install --save-dev electron-rebuild
# Every time you run "npm install", run this:
./node_modules/.bin/electron-rebuild
# Windows中如果你遇到了問題,請嘗試:
.\node_modules\.bin\electron-rebuild.cmd
<h3 id="manually-building-for-electron">手動編譯Electron</h3>
如果你是一個開發人員開發了一個native module并且想使用Electron測試它,你可能想要在Electron中手動重新編譯這個模塊。你可以直接使用node-gyp
在Electron中編譯:
cd /path-to-module/
HOME=~/.electron-gyp node-gyp rebuild --target=1.2.3 --arch=x64 --dist-url=https://atom.io/download/electron
HOME=~/.electron-gyp
是頭部地址。--target=1.2.3
是Electron的版本。--dist-url=...指明從哪里下載頭部。
--arch=x64`說明模塊在64位系統中編譯。
<h2 id="troubleshooting">排除故障</h2>
如果你安裝了一個native modules并且發現它沒有工作,你需要檢查以下方面:
- 模塊的架構是否和Electron的架構相同(ia32或者x64)。
- 你升級Electron之后,你是否重新編譯了模塊。
- 當有疑問的時候,首先應該重新運行
electron-rebuild
。
<h2 id="modules-that-rely-on-prebuild">依賴于<code>prebuild</code>的模塊</h2>
prebuild
提供一個方法,可以非常容易的使用預編譯二進制文件發布基于多個Electron和Node版本的native Node modules。
如果模塊提供Electron使用的二進制文件,為了充分的利用預編譯的二進制文件情確保刪掉--build-from-source
和npm_config_build_from_source
兩個環境變量。
<h2 id="modules-that-rely-on-node-pre-gyp">依賴于<code>node-pre-gyp</code>的模塊</h2>
node-pre-gyp
tool提供一個方法,可以使用預編譯二進制文件來展開/有效利用native Node modules,許多流行模塊都使用了這個。
通常這些模塊可以非常好的在Electron下工作,但是有時候當Electron使用了一個比Node新的版本的V8,并且有ABI改變的時候,不好的事情就會發生。所以通常情況下建議使用源代碼編譯本地模塊。
如果你遵循npm
的方式,則請在默認情況下安裝模塊,如果不是,則你需要在npm
中輸入--build-from-source
或者設置npm_config_build_from_source
環境變量。