Windows 使用 node-gyp

  • node 编译 c++ 扩展的时候使用的编译工具
  • depend on: python 2.7

开发一个 windows 小工具,工作 pc 是 ubuntu, 为了省事,选择用 electron,打算开发好了直接到 windows 上打包(ubuntu 上打 win 包还在研究中...)
本以为网上资料一大堆,找个能用的抄抄就好了,结果因为 node-gyp 编译问题扯了一天半还没解决...
大部分对 node-gyp 在 win 上的安装教程都是抄来抄去,其实就是同一篇文章,而且还不顶用, 猜测 npm 安装 windows-build-tools 可能需要参数辅助或其它支持...
实在受不了,只好花时间研究下 win 环境的 node-gyp 编译工具如何正确安装使用,在此作个记录

分 2 种情况:

Not exist Node

  1. 下载 .msi 安装包 https://nodejs.org

  2. 安装时(最好管理员运行)勾选:Automatically install the necessary tools ...

  3. 等待 安装程序 和 PowerShell 都执行完成

Already exist Node

包括 nvm 管理的 node

refer to:

  • https://github.com/nodejs/node-gyp
  • https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules
  • https://github.com/nodejs/node-gyp/issues/762
  • https://nodejs.org/api/addons.html
  • https://www.jianshu.com/p/af7f4bac2b0c
  • https://blog.csdn.net/qq_33826977/article/details/78620363

setp

  1. install Chocolatey (powershell or cmd)

    // powershell (admin)
    Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
    
    // cmd (admin)
    @"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
    
  2. install windows-build-tools by Chocolatey

    // install: Visual C++ Build Tools
    // powershell/cmd (admin)
    choco install visualcpp-build-tools
    
    -   options: A
    
  3. 如果未安装 python

    • choco install python2
  4. npm i -g node-gyp

  5. npm config set msvs_version 2017 -g

  6. node-gyp install

    • powershell 需要修改执行策略, 执行:set-ExecutionPolicy RemoteSigned
  7. node-gyp configure --msvs_version=2017

    • 可忽略如下错误
    gyp: binding.gyp not found (cwd: C:\Windows\system32) while trying to load binding.gyp
    gyp ERR! stack Error: `gyp` failed with exit code: 1
    
  8. [可选]resolve error: if not defined npm_config_node_gyp

    windows 中 2 选 1 即可

    • npm config set node_gyp "C:\Users\usr\AppData\Roaming\nvm\v12.14.1\node_modules\node-gyp\bin\node-gyp.js" -g
    • set npm_config_node_gyp=node C:\Users\usr\AppData\Roaming\npm\node_modules\node-gyp\bin\node-gyp.js -g
  9. test: npm i -S

    • mcrypt
    • sqlite3
    • node-sass
    • kerberos

你可能感兴趣的:(Windows 使用 node-gyp)