使用原生 Node 模組


使用 NPM 安裝

適用於 LTS 版本

使用相同版本的 Node.js 和 NW.js 架構

僅當您使用相同版本的 Node.js 和 NW.js 架構時,下列說明才會有效。

如果您使用 LTS 版本,則透過下列駭客手法安裝的原生模組將獲得支援

適用於非 LTS 版本

如果您使用的是非 LTS 版本,則由於 V8 中的 ABI 差異,必須先在全球預先安裝 nw-gyp 才能建置模組。以下說明也適用於 LTS 版本。

若要安裝 NW.js 的原生模組,請在您的終端機執行下列指令

# Install nw-gyp globally
npm install -g nw-gyp
# Setup target NW.js version
export npm_config_target=0.18.5
# Setup build architecture, ia32 or x64
export npm_config_arch=x64
export npm_config_target_arch=x64
# Setup env for modules built with node-pre-gyp
export npm_config_runtime=node-webkit
export npm_config_build_from_source=true
# Setup nw-gyp as node-gyp
export npm_config_node_gyp=$(which nw-gyp)
# Run npm install
npm install

Windows 注意事項

您需要安裝編譯器。您可以透過安裝 Visual C++ Build Tools 來取得編譯器。您還需要 Python 2.7(不支援版本 3.x)。
npm_config_node_gyp 環境變數必須設定為 path\to\global\node_modules\nw-gyp\bin\nw-gyp.js,而不是 nw-gyp.cmd 批次指令碼。這是 npm 的錯誤

您必須在 Windows 中使用 set 而不是 export 來設定環境變數。以下是完整的範例(Windows 10,Visual C++ Build Tool v2015)

set PYTHON=C:\Python27\python.exe
set npm_config_target=0.21.6
set npm_config_arch=x64
set npm_config_runtime=node-webkit
set npm_config_build_from_source=true
set npm_config_node_gyp=C:\Users\xxxxxxxxx\AppData\Roaming\npm\node_modules\nw-gyp\bin\nw-gyp.js
npm install --msvs_version=2015

手動重新建置

建議進行完整的 NPM 安裝

在切換 NW.js 版本後,建議的做法是刪除 node_modules 資料夾,並執行完整的 npm 安裝,如 上述說明

切換到新版本的 NW.js 後,您可以使用以下工具重建每個原生模組,無需重新安裝所有模組。由於建置原生模組需要 binding.gyp,因此您可以透過尋找 binding.gyp 檔案來輕鬆找到所有原生模組。

重建所有原生模組

請務必重建所有原生模組。否則您會遇到各種問題,甚至崩潰。如果手動重建對您不起作用,請嘗試執行完整的 npm 安裝。

nw-gyp

nw-gypnode-gyp 的一個 hack,用於支援 NW.js 特定的標頭和函式庫。

用法與 node-gyp 相同,但您需要手動指定 NW.js 的版本和架構 (x64ia32)。

npm install -g nw-gyp
cd myaddon
nw-gyp rebuild --target=0.13.0 --arch=x64

請參閱 https://github.com/nwjs/nw-gyp 以取得更多詳細資訊。

node-pre-gyp

有些套件使用 node-pre-gyp,它支援使用 node-gypnw-gyp 為 Node.js 和 NW.js 建置。

node-pre-gyp 的用法如下

npm install -g node-pre-gyp
cd myaddon
node-pre-gyp build --runtime=node-webkit --target=0.13.0 --target_arch=x64

請參閱 https://github.com/mapbox/node-pre-gyp 以取得更多詳細資訊。