node-gyp windows安装
545字约2分钟
2024-12-11
node-gyp 在 windows 下安装有很多依赖,比如安装 Microsoft VC++ 运行环境等,现记录有效安装的完整过程。
1. 安装必要的构建工具 windows-build-tools
确保你已经安装了适用于 Windows 的构建工具。你可以使用 windows-build-tools 自动安装这些工具。
安装 windows-build-tools
打开 PowerShell 或命令提示符(以管理员身份运行),然后运行以下命令:
npm install --global windows-build-tools注意
nodejs 安装 ffi 报错, windows-build-tools 安装不成功。
windows-build-tools 只能使用 v17.x 的 nodejs 版本安装。
这将自动安装以下内容:
- Python 2.7.x
 - Visual Studio Build Tools 2017 (包括 C++ 构建工具)
 
2. 检查环境变量
确保你的系统环境变量中包含了必要的路径。
检查 PATH 环境变量 确保 PATH 环境变量中包含了 Python 和 Visual Studio 的相关路径。例如:
- Python: 
C:\Users\<YourUsername>\.windows-build-tools\python27\ - Visual Studio: 
C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC\<Version>\bin\Hostx64\x64\ 
3. 配置 node-gyp 使用正确的 Visual Studio 版本
即使安装了 windows-build-tools,有时 node-gyp 仍然需要显式指定 Visual Studio 版本。
设置 msvs_version
你可以通过以下命令设置 msvs_version, windows-build-tools 安装的是 2017 Visual Studio 版本:
npm config set msvs_version 20174. 更新 node-gyp
确保你使用的是最新版本的 node-gyp。
npm install -g node-gyp5. 清理并重新配置 node-gyp
有时缓存和配置文件可能会导致问题。你可以尝试清理并重新配置 node-gyp。
node-gyp clean
node-gyp configure
node-gyp build6. 示例
demo.cpp
#include <node_api.h>
namespace demo {
napi_value Method(napi_env env, napi_callback_info args) {
  napi_value greeting;
  napi_status status;
  status = napi_create_string_utf8(env, "hello world", NAPI_AUTO_LENGTH, &greeting);
  if (status != napi_ok) return nullptr;
  return greeting;
}
napi_value init(napi_env env, napi_value exports) {
  napi_status status;
  napi_value fn;
  status = napi_create_function(env, nullptr, 0, Method, nullptr, &fn);
  if (status != napi_ok) return nullptr;
  status = napi_set_named_property(env, exports, "hello", fn);
  if (status != napi_ok) return nullptr;
  return exports;
}
NAPI_MODULE(NODE_GYP_MODULE_NAME, init)
}  // namespace demobinding.gyp 构建配置文件
{
  "targets": [
    {
      "target_name": "demo",
      "sources": [ "demo.cc" ]
    }
  ]
}在项目下运行构建命令,生成的文件在 build 目录下。
node-gyp configure build