NPM是随同NodeJS一起安装的包管理工具,解决前端JS打包的问题,npm 全称 node package manager,是 js 的包管理工具,开发人员可以把写好的框架、库发布到 npm 上,使用者在使用时候就可很方便地通过 npm 来下载。NPM是前端开发广泛使用的包管理工具。类似后端的composer
安装 nodejs
sudo apt-get install -y nodejs
#离线安装
cd /usr/local/node/
wget https://npm.taobao.org/mirrors/node/v14.17.6/node-v14.17.6-linux-x64.tar.gz
tar -zxvf node-v14.17.6.tar.gz
ln -s /usr/local/node/node-v14.17.6-linux-x64/bin/npm /usr/bin/npm
ln -s /usr/local/node/node-v14.17.6-linux-x64/bin/node /usr/bin/node
查看node安装成功
node -v
npm是否包含
npm -v
下载好 node.js, npm 也就有了 npm更新地可比 node 勤快多了,因此你下载的 node 附带的 npm 版本可能不是最新的,你可以使用如下命令下载最新 npm:
npm install npm@latest -g
设置国内镜像
npm config set registry http://registry.npm.taobao.org/
检查换成功
npm config get registry
安装 webpack
webpack是模块打包机,把 css、js、less 等打包成一个总的js文件供浏览器使用
npm install webpack -g
webpack-dev-server就是一个小型的静态文件服务器。使用它,可以为webpack打包生成的资源文件提供Web服务。
安装 Yarn
Yarn是Facebook最近发布的一款依赖包安装工具。Yarn是一个新的快速安全可信赖的可以替代NPM的依赖管理工具
npm install -g yarn
yarn config set registry http://registry.npm.taobao.org/
如果在你的项目里有 package.json 文件,运行 npm install 后它会查找文件中列出的依赖包,然后下载符合语义化版本规则的版本。npm install 默认会安装 package.json 中 dependencies 和 devDependencies 里的所有模块。
下载包
npm install <package_name>
//yarn install
后面就是要安装包的名称。这个命令会在当前目录创建一个 node_modules 目录,然后下载我们指定的包到这个目录中
编译生成html页面或JS
yarn build或者npm run build是执行配置在package.json中的脚本,比如:
"scripts": {
"dev": "node build/dev-server.js",
"build": "node build/build.js",
"unit": "karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
},
只有这里配置了,你才能run,所以不是所有的项目都能npm run dev/build。要了解这些命令做了什么,就要去scripts中看具体执行的是什么代码。这里就像是一些命令的快捷方式,免去每次都要输入很长的的命令
报错
yarn add v1.6.0
warning package.json: No license field
warning No license field
[1/4] Resolving packages...
[2/4] Fetching packages...
info fsevents@1.2.3: The platform "linux" is incompatible with this module.
info "fsevents@1.2.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
error An unexpected error occurred: "ENOTSUP: operation not supported on socket, symlink '../../../acorn/bin/acorn' -> '/mnt/hgfs/workspace/temp/nodetest/node_modules/acorn-dynamic-import/node_modules/.bin/acorn'".
info If you think this is a bug, please open a bug report with the information provided in "/mnt/hgfs/workspace/temp/nodetest/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
解决方法
yarn install --no-bin-links
在进行npm run build时报错:
sh: 1: cross-env: not found
"scripts": {
"start": "cross-env REACT_APP_API=xxx.xxx.xxx node scripts/start.js",
"build": "cross-env node scripts/build.js",
删除cross-env,更新代码时把线上环境的cross-env删除掉