原文:https://github.com/electron/electron/blob/master/docs/tutorial/using-native-node-modules.md
譯者:Lin
Electron支持native Node modules切诀,但是因為Electron非常有可能從安裝在你系統(tǒng)的Node二進制文件中使用一個不同版本的V8绰寞,你必須要在編譯native modules時手動指定本地Electron頭部熊锭。
<h2 id="how-to-install-native-modules">如何安裝本地模塊</h2>
三種方法安裝native modules:
<h3 id="using-npm">使用<code>npm</code></h3>
通過設(shè)置一些環(huán)境變量,你可以直接使用npm
來安裝模塊枉证。
一個Electron所有依賴的例子:
# Electron的版本阱州。
export npm_config_target=1.2.3
# Electron架構(gòu),可以是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的版本并且處理手動步驟中的下載頭部和為你的應(yīng)用編譯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>
如果你是一個開發(fā)人員開發(fā)了一個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位系統(tǒng)中編譯聋迎。
<h2 id="troubleshooting">排除故障</h2>
如果你安裝了一個native modules并且發(fā)現(xiàn)它沒有工作脂矫,你需要檢查以下方面:
- 模塊的架構(gòu)是否和Electron的架構(gòu)相同(ia32或者x64)。
- 你升級Electron之后霉晕,你是否重新編譯了模塊庭再。
- 當(dāng)有疑問的時候,首先應(yīng)該重新運行
electron-rebuild
娄昆。
<h2 id="modules-that-rely-on-prebuild">依賴于<code>prebuild</code>的模塊</h2>
prebuild
提供一個方法佩微,可以非常容易的使用預(yù)編譯二進制文件發(fā)布基于多個Electron和Node版本的native Node modules。
如果模塊提供Electron使用的二進制文件萌焰,為了充分的利用預(yù)編譯的二進制文件情確保刪掉--build-from-source
和npm_config_build_from_source
兩個環(huán)境變量哺眯。
<h2 id="modules-that-rely-on-node-pre-gyp">依賴于<code>node-pre-gyp</code>的模塊</h2>
node-pre-gyp
tool提供一個方法,可以使用預(yù)編譯二進制文件來展開/有效利用native Node modules扒俯,許多流行模塊都使用了這個奶卓。
通常這些模塊可以非常好的在Electron下工作,但是有時候當(dāng)Electron使用了一個比Node新的版本的V8撼玄,并且有ABI改變的時候夺姑,不好的事情就會發(fā)生。所以通常情況下建議使用源代碼編譯本地模塊掌猛。
如果你遵循npm
的方式盏浙,則請在默認(rèn)情況下安裝模塊,如果不是,則你需要在npm
中輸入--build-from-source
或者設(shè)置npm_config_build_from_source
環(huán)境變量废膘。