本文介绍在Debian 10操作系统上安装Node.js和npm的三种不同方法,包括卸载Node.js的方法。你选择安装的方法取决于你的要求和偏好,以下为你详细介绍。

本文介绍在Debian 10操作系统上安装Node.js和npm的三种不同方法,包括卸载Node.js的方法。你选择安装的方法取决于你的要求和偏好,以下为你详细介绍。

在Debian 10系统上安装Node.js和npm的三种不同方法

方法一、从Debian存储库安装Node.js和npm

Node.js和npm可以从标准的Debian存储库安装,在选写本文时,存储库中的版本是v10.x,这是最新的LTS版本。

要在Debian上安装Node.js和npm,请使用以下命令:

sudo apt update
sudo apt install nodejs npm

一个安装完成,通过键入以下命令进行验证:

nodejs --version

该命令将显示Node.js版本:

v10.15.2

注:这是在Debian上安装Node.js和npm的最简单方法,对大多数用例来说应该足够了。

方法二、从NodeSource存储库安装Node.js和npm

NodeSource是一家专注于提供企业级Node支持的公司,它维护一个包含多个Node.js版本的APT存储库。

如果需要安装特定版本的Node.js,请使用此存储库,在选写本文时,NodeSource存储库提供的版本有v12.x(最新的稳定版本)、v11.x、v10.x(最新的LTS版本)、v8.x(之前的LTS版本)。

我们将安装Node.js版本12.x。

首先,通过运行以下curl命令将NodeSource存储库添加到系统中:

curl -sL https://deb.nodesource.com/setup_12.x | sudo bash -

添加存储库以安装Node.js和npm类型后:

sudo apt install nodejs

键入以下命令确保已正确安装Node.js:

node --version

返回信息如下:

v12.8.1

方法三、使用NVM安装Node.js和npm

NVM(节点版本管理器)是一个bash脚本,允许你管理多个Node.js版本,使用NVM,你可以安装和卸载要使用或测试的任何Node.js版本。

如果要基于每个用户安装Node.js,请使用此方法。

要在系统上安装NVM,请键入以下命令,不要使用sudo,因为它将为root用户启用脚本:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
#或者
git clone https://github.com/creationix/nvm.git
cd ~

#添加环境配置.bashrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

#添加环境配置.profile
# ~/.profile: executed by Bourne-compatible login shells.
if [ "$BASH" ]; then
  if [ -f ~/.bashrc ]; then
    . ~/.bashrc
  fi
fi
mesg n || true
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
#!/usr/bin/env bash

{ # this ensures the entire script is downloaded #

nvm_has() {
  type "$1" > /dev/null 2>&1
}

nvm_install_dir() {
  if [ -n "$NVM_DIR" ]; then
    printf %s "${NVM_DIR}"
  elif [ -n "$XDG_CONFIG_HOME" ]; then
    printf %s "${XDG_CONFIG_HOME/nvm}"
  else
    printf %s "$HOME/.nvm"
  fi
}

nvm_latest_version() {
  echo "v0.34.0"
}

nvm_profile_is_bash_or_zsh() {
  local TEST_PROFILE
  TEST_PROFILE="${1-}"
  case "${TEST_PROFILE-}" in
    *"/.bashrc" | *"/.bash_profile" | *"/.zshrc")
      return
    ;;
    *)
      return 1
    ;;
  esac
}

#
# Outputs the location to NVM depending on:
# * The availability of $NVM_SOURCE
# * The method used ("script" or "git" in the script, defaults to "git")
# NVM_SOURCE always takes precedence unless the method is "script-nvm-exec"
#
nvm_source() {
  local NVM_METHOD
  NVM_METHOD="$1"
  local NVM_SOURCE_URL
  NVM_SOURCE_URL="$NVM_SOURCE"
  if [ "_$NVM_METHOD" = "_script-nvm-exec" ]; then
    NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm-exec"
  elif [ "_$NVM_METHOD" = "_script-nvm-bash-completion" ]; then
    NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/bash_completion"
  elif [ -z "$NVM_SOURCE_URL" ]; then
    if [ "_$NVM_METHOD" = "_script" ]; then
      NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm.sh"
    elif [ "_$NVM_METHOD" = "_git" ] || [ -z "$NVM_METHOD" ]; then
      NVM_SOURCE_URL="https://github.com/creationix/nvm.git"
    else
      echo >&2 "Unexpected value \"$NVM_METHOD\" for \$NVM_METHOD"
      return 1
    fi
  fi
  echo "$NVM_SOURCE_URL"
}

#
# Node.js version to install
#
nvm_node_version() {
  echo "$NODE_VERSION"
}

nvm_download() {
  if nvm_has "curl"; then
    curl --compressed -q "$@"
  elif nvm_has "wget"; then
    # Emulate curl with wget
    ARGS=$(echo "$*" | command sed -e 's/--progress-bar /--progress=bar /' \
                            -e 's/-L //' \
                            -e 's/--compressed //' \
                            -e 's/-I /--server-response /' \
                            -e 's/-s /-q /' \
                            -e 's/-o /-O /' \
                            -e 's/-C - /-c /')
    # shellcheck disable=SC2086
    eval wget $ARGS
  fi
}

install_nvm_from_git() {
  local INSTALL_DIR
  INSTALL_DIR="$(nvm_install_dir)"

  if [ -d "$INSTALL_DIR/.git" ]; then
    echo "=> nvm is already installed in $INSTALL_DIR, trying to update using git"
    command printf '\r=> '
    command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" fetch origin tag "$(nvm_latest_version)" --depth=1 2> /dev/null || {
      echo >&2 "Failed to update nvm, run 'git fetch' in $INSTALL_DIR yourself."
      exit 1
    }
  else
    # Cloning to $INSTALL_DIR
    echo "=> Downloading nvm from git to '$INSTALL_DIR'"
    command printf '\r=> '
    mkdir -p "${INSTALL_DIR}"
    if [ "$(ls -A "${INSTALL_DIR}")" ]; then
      command git init "${INSTALL_DIR}" || {
        echo >&2 'Failed to initialize nvm repo. Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" remote add origin "$(nvm_source)" 2> /dev/null \
        || command git --git-dir="${INSTALL_DIR}/.git" remote set-url origin "$(nvm_source)" || {
        echo >&2 'Failed to add remote "origin" (or set the URL). Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" fetch origin tag "$(nvm_latest_version)" --depth=1 || {
        echo >&2 'Failed to fetch origin with tags. Please report this!'
        exit 2
      }
    else
      command git -c advice.detachedHead=false clone "$(nvm_source)" -b "$(nvm_latest_version)" --depth=1 "${INSTALL_DIR}" || {
        echo >&2 'Failed to clone nvm repo. Please report this!'
        exit 2
      }
    fi
  fi
  command git -c advice.detachedHead=false --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" checkout -f --quiet "$(nvm_latest_version)"
  if [ -n "$(command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" show-ref refs/heads/master)" ]; then
    if command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet 2>/dev/null; then
      command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet -D master >/dev/null 2>&1
    else
      echo >&2 "Your version of git is out of date. Please update it!"
      command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch -D master >/dev/null 2>&1
    fi
  fi

  echo "=> Compressing and cleaning up git repository"
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" reflog expire --expire=now --all; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" gc --auto --aggressive --prune=now ; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  return
}

#
# Automatically install Node.js
#
nvm_install_node() {
  local NODE_VERSION_LOCAL
  NODE_VERSION_LOCAL="$(nvm_node_version)"

  if [ -z "$NODE_VERSION_LOCAL" ]; then
    return 0
  fi

  echo "=> Installing Node.js version $NODE_VERSION_LOCAL"
  nvm install "$NODE_VERSION_LOCAL"
  local CURRENT_NVM_NODE

  CURRENT_NVM_NODE="$(nvm_version current)"
  if [ "$(nvm_version "$NODE_VERSION_LOCAL")" == "$CURRENT_NVM_NODE" ]; then
    echo "=> Node.js version $NODE_VERSION_LOCAL has been successfully installed"
  else
    echo >&2 "Failed to install Node.js $NODE_VERSION_LOCAL"
  fi
}

install_nvm_as_script() {
  local INSTALL_DIR
  INSTALL_DIR="$(nvm_install_dir)"
  local NVM_SOURCE_LOCAL
  NVM_SOURCE_LOCAL="$(nvm_source script)"
  local NVM_EXEC_SOURCE
  NVM_EXEC_SOURCE="$(nvm_source script-nvm-exec)"
  local NVM_BASH_COMPLETION_SOURCE
  NVM_BASH_COMPLETION_SOURCE="$(nvm_source script-nvm-bash-completion)"

  # Downloading to $INSTALL_DIR
  mkdir -p "$INSTALL_DIR"
  if [ -f "$INSTALL_DIR/nvm.sh" ]; then
    echo "=> nvm is already installed in $INSTALL_DIR, trying to update the script"
  else
    echo "=> Downloading nvm as script to '$INSTALL_DIR'"
  fi
  nvm_download -s "$NVM_SOURCE_LOCAL" -o "$INSTALL_DIR/nvm.sh" || {
    echo >&2 "Failed to download '$NVM_SOURCE_LOCAL'"
    return 1
  } &
  nvm_download -s "$NVM_EXEC_SOURCE" -o "$INSTALL_DIR/nvm-exec" || {
    echo >&2 "Failed to download '$NVM_EXEC_SOURCE'"
    return 2
  } &
  nvm_download -s "$NVM_BASH_COMPLETION_SOURCE" -o "$INSTALL_DIR/bash_completion" || {
    echo >&2 "Failed to download '$NVM_BASH_COMPLETION_SOURCE'"
    return 2
  } &
  for job in $(jobs -p | command sort)
  do
    wait "$job" || return $?
  done
  chmod a+x "$INSTALL_DIR/nvm-exec" || {
    echo >&2 "Failed to mark '$INSTALL_DIR/nvm-exec' as executable"
    return 3
  }
}

nvm_try_profile() {
  if [ -z "${1-}" ] || [ ! -f "${1}" ]; then
    return 1
  fi
  echo "${1}"
}

#
# Detect profile file if not specified as environment variable
# (eg: PROFILE=~/.myprofile)
# The echo'ed path is guaranteed to be an existing file
# Otherwise, an empty string is returned
#
nvm_detect_profile() {
  if [ "${PROFILE-}" = '/dev/null' ]; then
    # the user has specifically requested NOT to have nvm touch their profile
    return
  fi

  if [ -n "${PROFILE}" ] && [ -f "${PROFILE}" ]; then
    echo "${PROFILE}"
    return
  fi

  local DETECTED_PROFILE
  DETECTED_PROFILE=''

  if [ -n "${BASH_VERSION-}" ]; then
    if [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    fi
  elif [ -n "${ZSH_VERSION-}" ]; then
    DETECTED_PROFILE="$HOME/.zshrc"
  fi

  if [ -z "$DETECTED_PROFILE" ]; then
    for EACH_PROFILE in ".profile" ".bashrc" ".bash_profile" ".zshrc"
    do
      if DETECTED_PROFILE="$(nvm_try_profile "${HOME}/${EACH_PROFILE}")"; then
        break
      fi
    done
  fi

  if [ -n "$DETECTED_PROFILE" ]; then
    echo "$DETECTED_PROFILE"
  fi
}

#
# Check whether the user has any globally-installed npm modules in their system
# Node, and warn them if so.
#
nvm_check_global_modules() {
  command -v npm >/dev/null 2>&1 || return 0

  local NPM_VERSION
  NPM_VERSION="$(npm --version)"
  NPM_VERSION="${NPM_VERSION:--1}"
  [ "${NPM_VERSION%%[!-0-9]*}" -gt 0 ] || return 0

  local NPM_GLOBAL_MODULES
  NPM_GLOBAL_MODULES="$(
    npm list -g --depth=0 |
    command sed -e '/ npm@/d' -e '/ (empty)$/d'
  )"

  local MODULE_COUNT
  MODULE_COUNT="$(
    command printf %s\\n "$NPM_GLOBAL_MODULES" |
    command sed -ne '1!p' |                     # Remove the first line
    wc -l | command tr -d ' '                   # Count entries
  )"

  if [ "${MODULE_COUNT}" != '0' ]; then
    # shellcheck disable=SC2016
    echo '=> You currently have modules installed globally with `npm`. These will no'
    # shellcheck disable=SC2016
    echo '=> longer be linked to the active version of Node when you install a new node'
    # shellcheck disable=SC2016
    echo '=> with `nvm`; and they may (depending on how you construct your `$PATH`)'
    # shellcheck disable=SC2016
    echo '=> override the binaries of modules installed with `nvm`:'
    echo

    command printf %s\\n "$NPM_GLOBAL_MODULES"
    echo '=> If you wish to uninstall them at a later point (or re-install them under your'
    # shellcheck disable=SC2016
    echo '=> `nvm` Nodes), you can remove them from the system Node as follows:'
    echo
    echo '     $ nvm use system'
    echo '     $ npm uninstall -g a_module'
    echo
  fi
}

nvm_do_install() {
  if [ -n "${NVM_DIR-}" ] && ! [ -d "${NVM_DIR}" ]; then
    echo >&2 "You have \$NVM_DIR set to \"${NVM_DIR}\", but that directory does not exist. Check your profile files and environment."
    exit 1
  fi
  if [ -z "${METHOD}" ]; then
    # Autodetect install method
    if nvm_has git; then
      install_nvm_from_git
    elif nvm_has nvm_download; then
      install_nvm_as_script
    else
      echo >&2 'You need git, curl, or wget to install nvm'
      exit 1
    fi
  elif [ "${METHOD}" = 'git' ]; then
    if ! nvm_has git; then
      echo >&2 "You need git to install nvm"
      exit 1
    fi
    install_nvm_from_git
  elif [ "${METHOD}" = 'script' ]; then
    if ! nvm_has nvm_download; then
      echo >&2 "You need curl or wget to install nvm"
      exit 1
    fi
    install_nvm_as_script
  else
    echo >&2 "The environment variable \$METHOD is set to \"${METHOD}\", which is not recognized as a valid installation method."
    exit 1
  fi

  echo

  local NVM_PROFILE
  NVM_PROFILE="$(nvm_detect_profile)"
  local PROFILE_INSTALL_DIR
  PROFILE_INSTALL_DIR="$(nvm_install_dir | command sed "s:^$HOME:\$HOME:")"

  SOURCE_STR="\\nexport NVM_DIR=\"${PROFILE_INSTALL_DIR}\"\\n[ -s \"\$NVM_DIR/nvm.sh\" ] && \\. \"\$NVM_DIR/nvm.sh\"  # This loads nvm\\n"

  # shellcheck disable=SC2016
  COMPLETION_STR='[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion\n'
  BASH_OR_ZSH=false

  if [ -z "${NVM_PROFILE-}" ] ; then
    local TRIED_PROFILE
    if [ -n "${PROFILE}" ]; then
      TRIED_PROFILE="${NVM_PROFILE} (as defined in \$PROFILE), "
    fi
    echo "=> Profile not found. Tried ${TRIED_PROFILE-}~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile."
    echo "=> Create one of them and run this script again"
    echo "   OR"
    echo "=> Append the following lines to the correct file yourself:"
    command printf "${SOURCE_STR}"
    echo
  else
    if nvm_profile_is_bash_or_zsh "${NVM_PROFILE-}"; then
      BASH_OR_ZSH=true
    fi
    if ! command grep -qc '/nvm.sh' "$NVM_PROFILE"; then
      echo "=> Appending nvm source string to $NVM_PROFILE"
      command printf "${SOURCE_STR}" >> "$NVM_PROFILE"
    else
      echo "=> nvm source string already in ${NVM_PROFILE}"
    fi
    # shellcheck disable=SC2016
    if ${BASH_OR_ZSH} && ! command grep -qc '$NVM_DIR/bash_completion' "$NVM_PROFILE"; then
      echo "=> Appending bash_completion source string to $NVM_PROFILE"
      command printf "$COMPLETION_STR" >> "$NVM_PROFILE"
    else
      echo "=> bash_completion source string already in ${NVM_PROFILE}"
    fi
  fi
  if ${BASH_OR_ZSH} && [ -z "${NVM_PROFILE-}" ] ; then
    echo "=> Please also append the following lines to the if you are using bash/zsh shell:"
    command printf "${COMPLETION_STR}"
  fi

  # Source nvm
  # shellcheck source=/dev/null
  \. "$(nvm_install_dir)/nvm.sh"

  nvm_check_global_modules

  nvm_install_node

  nvm_reset

  echo "=> Close and reopen your terminal to start using nvm or run the following to use it now:"
  command printf "${SOURCE_STR}"
  if ${BASH_OR_ZSH} ; then
    command printf "${COMPLETION_STR}"
  fi
}

#
# Unsets the various functions defined
# during the execution of the install script
#
nvm_reset() {
  unset -f nvm_has nvm_install_dir nvm_latest_version nvm_profile_is_bash_or_zsh \
    nvm_source nvm_node_version nvm_download install_nvm_from_git nvm_install_node \
    install_nvm_as_script nvm_try_profile nvm_detect_profile nvm_check_global_modules \
    nvm_do_install nvm_reset
}

[ "_$NVM_ENV" = "_testing" ] || nvm_do_install

} # this ensures the entire script is downloaded #

安装脚本将nvm存储库从Github克隆到~/.nvm目录,并将nvm路径添加到Bash或ZSH配置文件中:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

要开始使用nvm脚本,请打开新的shell会话或运行屏幕上打印的命令,做任何更容易的事情。

现在你的Debian系统上安装了nvm脚本,你可以安装最新的稳定版Node.js:

nvm install node

返回信息如下:

Computing checksum with sha256sum
Checksums matched!
Now using node v12.8.1 (npm v6.10.2)
Creating default alias: default -> node (-> v12.8.1)

让我们再安装两个版本,最新的LTS版本和版本8.16.0:

nvm install --lts
nvm install 8.16.0

完成后,列出所有已安装的Node.js版本类型:

nvm ls

带箭头的条目(即-> v8.16.0)是当前shell会话中使用的版本,默认版本设置为v12.8.1,默认版本是打开新shell会话时将使用的版本。

如果你想更改当前活动的版本,运行如以下命令:

nvm use 8.11.3

要更改默认的Node.js,例如更改为v10.16.2,请使用:

nvm alias default 8.11.3

附1:安装开发工具

开发工具是从npm注册表编译和安装本机加载项所必需的,通过运行安装包:

sudo apt install build-essential

附2:卸载Node.js的方法

如果由于某些原因要卸载Node.js和npm软件包,请使用以下命令:

sudo apt remove nodejs npm

注:命令运行完后即已从系统中删除掉Node.js和npm软件包。

附3:安装创建vue方法

#先清除原来的
npm uninstall -g @vue/cli
#vue-cli安装
npm install -g @vue/cli
#安装淘宝镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
#查看淘宝镜像
cnpm -v
#安装
cnpm install -g @vue/cli
#查看安装文件(大写V)
vue -V
#创建vue项目
cd /mnt/prjs
vue create vue
#报错sh: 1: node: Permission denied
npm config set user 0
npm config set unsafe-perm true
#报错npm ERR! code ENOENT
npm install -g npm  //补全报错文件件
npm cache clean --force //清理缓存
npm update -g npm
npm i #重新安装
npm config set registry https://registry.npm.taobao.org
npm config set disturl https://npm.taobao.org/dist
#启动vue项目
cd vue
cnpm install vue-router@3.2.0 --save
#安装框架element
npm i element-ui -S --legacy-peer-deps
#启动项目
npm run serve
#报错npm ERR! code ERESOLVE
#解决办法有两种:
#1.在命令后加上--legacy-peer-deps
#2.使用npm6.x
#提示:使用npm@6不需要卸载npm@7。可以使用npx指定npm的版本。例如:npx -p npm@6 npm i --legacy-peer-deps
#如果这不能立即起作用,可以先删除node_modules和package-lock.json

自动化重启

#安装nodemon插件
npm install --save-dev nodemon
#在项目的package.json文件中的scripts对象下添加开启nodemon的操作
"scripts": {
   "serve": "vue-cli-service serve",
   "build": "vue-cli-service build",
   "lint": "vue-cli-service lint",
   "dev": "vue-cli-service serve",
   "start": "nodemon"
 },
#在项目根目录下创建nodemon.json文件
{
  "restartable": "rs",
  "verbose": true,
  "ignore": ["node_modules", ".git"],
  "exec": "vue-cli-service serve",
  "execMap": {
    "": "node",
    "js": "node --harmony"
  },
  "events": {
    "restart": "osascript -e 'display notification \"App restarted due to:\n'$FILENAME'\" with title \"nodemon\"'"
  },
  "watch": ["src"], 
  "env": {
    "NODE_ENV": "development",
    "PORT": "3000"
  },
  "ext": "js json",
  "legacy-watch": false
}
#修改vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  devServer: {
      host: '0.0.0.0',
      //https:true,
      port: 3000,
      client: {
        webSocketURL: 'ws://0.0.0.0:3000/ws',
      },
      headers: {
        'Access-Control-Allow-Origin': '*',
      }
  },
  transpileDependencies: true
})

ignore是指不进行监听的文件;exec是监听到文件变化后执行的代码;watch是监听的文件名
在运行项目时,需要顺便运行nodemon,即npm run start,之后在更改proxy.js文件时就会自动跑一遍npm run serve重启服务器。

附4:yarn详细入门教程

Yarn 是 Facebook, Google, Exponent 和 Tilde 开发的一款新的 JavaScript 包管理工具。解决这些团队使用 npm 面临的少数问题,即:

  1. 安装的时候无法保证速度/一致性
  2. 安全问题,因为 npm 安装时允许运行代码

Yarn 同样是一个从 npm 注册源获取模块的新的 CLI 客户端。注册的方式不会有任何变化 —— 你同样可以正常获取与发布包。

安装

1.进入官方下载页面安装

2.最简单的方法是运行:

npm install -g yarn

现在的yarn安装页面是这么说的:

注意:通常情况下不建议通过npm进行安装。npm安装是非确定性的,程序包没有签名,并且npm除了做了基本的SHA1哈希之外不执行任何完整性检查,这给安装系统程序带来了安全风险。

基于这些原因,强烈建议你通过最适合于你的操作系统的安装方法来安装yarn。

以这种速度发展下去的话,如果yarn要宣布他们自己的registry,让开发者慢慢淘汰npm的话,我们一点都不会感到惊讶。

安装成功后即可查看版本:

yarn --version

初始化

进入项目目录下并执行 yarn init
会在根目录下生成一个package.json,与npm类似具体不做解释

添加依赖

  1. 添加包:yarn add [pkg-name] ,会自动安装最新版本,会覆盖指定版本号
    #举例添加 jquery
    yarn add jquery

node_modules下会生成 jquery 文件夹,里面便是 yarn 生成的依赖

  1. 一次性添加多个包:yarn add [pkg-name1] [pkg-name2]
    举例添加 bootstrap 和 zepto:yarn add bootstrap zepto
  2. 添加指定版本的包:yarn add [pkg-name]@ver
    举例添加 2.1.4版本的jquery:yarn add jquery@2.1.4
  3. 将包更新到指定版本:yarn upgrade [pkg-name]@ver
    举例将 jquery从2.1.4更新到3.0.0版本:yarn upgrade jquery@3.0.0
  4. 将包更新到最新版本:yarn upgrade --latest [pkg-name]
    例将3.0.0版本的 jquery更新到最新版本:yarn upgrade --latest jquery
  5. 删除包:yarn remove [pkg-name]
    举例删除 jquery:yarn remove jquery
  6. 一次删除多个包:yarn remove [pkg-name1] [pkg-name2]
    举例删除 bootstrap 和 zepto:yarn remove bootstrap zepto

yarn.lock 自动锁定安装包版本

Npm 有一个名为 shrinkwrap 的特性,其目的是在生产环境中使用时锁定包依赖。shrinkwrap 的挑战是每个开发者都必须手动运行 npm shrinkwrap 生成 npm-shrinkwrap.json 文件。

使用 Yarn,则截然不同。在安装过程中,会自动生成一个 yarn.lock 文件,yarn.lock 会记录你安装的所有大大小小的。有点类似 PHP 开发者们所熟悉的 composer.lock。yarn.lock 锁定了安装包的精确版本以及所有依赖项,只要你不删除 yarn.lock 文件,再次运行 yarn install 时,会根据其中记录的版本号获取所有依赖包。有了这个文件,你可以确定项目团队的每个成员都安装了精确的软件包版本,部署可以轻松地重现,且没有意外的 bug。你可以把 yarn.lock 提交到本库里,这样其他签出代码并运行 yarn install 时,可以保证大家安装的依赖都是完全一致的。

例如上面安装的bootstrap、jquery和zepto会在yarn.lock中有记录

这里新建一个 yarn_demo2 的文件夹,并将 package.json 和 yarn.lock 文件从 yarn_demo 文件夹中复制过来

进入yarn_demo2 文件夹 执行 yarn 命令,即可一键下载 yarn.lock 中记录的依赖包,相当方便快捷,值得你拥有~

yarn和npm命令对比

npm-yarn.png