Npm tips

3.13

Speed up

Change a faster (but readonly) registry. For example

npm config set registry https://registry.npmmirror.com

Offical for publish:

https://registry.npmjs.org 

Upgrade

# Select version
nvm install 18

# Update project
rm -fr node_modules
npm update
npm install

Error: Cannot find module 'nan'

Solution:

npm i --no-optional

Ref

提交时自动 prettier

npm i husky pretty-quick prettier
  "husky": {
    "hooks": {
      "pre-commit": "pretty-quick --staged"
    }
  }

npm 包安全风险检测和修复

npm audit

npm audit fix

npm install 卡在 fetchMetadata ...

npm install gets stuck at fetchMetadata

npm install --verbose

查看详细信息。如果卡住某一步,可以看看package.json可能是某个包直接使用了 github 地址。例如

"react-native": "https://github.com/expo/react-native/archive/sdk-35.0.0.tar.gz",

npm 无法下载的情况下,可以先通过浏览器下载,再安装

npm install ./package.gz

加载 node_module 中特定的 css 和 js 文件

@import "~nprogress/nprogress.css";
import nprogress from "nprogress/nprogress.js";

npm link 使用本地任意位置的 node module

  1. 创建模块

    cd demo_module
    npm init -y
    
  2. demo_module链接到全局(demo_module)

    npm link
    

1) 在项目中建立到目标模块的链接(project)

    npm link demo_module
  1. 可以在项目中使用该模块了: require('demo_module')

unlink

  1. 取消demo_module的全局链接(demo_module)

    npm unlink
    
  2. 在项目中取消到目标模块的链接(project)

    npm unlink --no-save demo_module
    

node, npm 多版本管理

不同大版本的 node 和 npm 容易有兼容性问题。

一台机器上多版本的安装和切换

  • Linux: nvm

    wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash
    
  • Windows: nvm-windows

Linux 安装

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

或者

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash

安装完成后,需要

source ~/.bashrc

node 安装

  • 通常情况,可以在官网下载安装包或压缩包

  • Linux 下,可以下载 nvm, 使用 nvm 安装指定版本的 node

      yum install nvm
      nvm install 6.10
    

npm 发布包

设置要发布的仓库地址

npm config set registry https://registry.npmjs.org

包文件提交,package.json 符合格式要求后

npm login
npm version <new_version>
npm publish

npm 改变版本

# 安装最新版本
npm install npm@latest -g

# 安装特定版本
npm install npm@3.10.10 -g

# 普通模块的完整升级(以 angular-cli 为例)
npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

npm 相关目录

Win7 全局安装目录

~/AppData/Roaming/npm/

npm 混合私有仓库和公共仓库

企业有时候需要在私有仓库中上传和下载模块,需要配置 npm 优先使用私有仓库

使用私有仓库

npm config set registry http://myreg.mycompany.com:8080
npm login

https://myreg.mycompany.com:8800/settings默认开启"Read Through Cache" ,会镜像公共仓库

混合使用

npm login --registry=http://myreg.mycompany.com:8080 --scope=@myco

@myco开头的模块会走私有仓库,其余走公共仓库。

npm 报错

npm publish 报错:

no_perms Private mode enable, only admin can publish this module

解决

使用 nrm 改了仓库地址。发布时需要重新切换回官方仓库

nrm use npm

或者

npm config set registry https://registry.npmjs.org

npm install global 无法运行

package.json 的 bin 字段引用的文件需要以 `#!/usr/bin/env node`开头。

npm WARN checkPermissions Missing write access to ...

需要设置 node_modules 的所有者为当前用户

chown -R `whoami` node_modules
📖