npm

npm

在学习react的同时,顺带了解npm以及cnpm。

Node Package Manager,Node.js 的包管理工具,依赖 package.json 文件。

常用包命令

  • npm install xxx[@x.x.x]:安装[特定]版本
/*把依赖包名称添加到 package.json 文件 devDependencies 键下*/
/*devDependencies是开发时依赖*/
–save-dev: 安装开发环境需要的依赖包
/*把依赖包名称添加到 package.json 文件 dependencies 键下*/
/*dependencies是运行时依赖*/
–save : 安装生产环境需要的依赖包
  • npm info xxx:查看包的详细信息
  • npm ls xxx:查看包信息

关于npm install的介绍,参见:https://www.cnblogs.com/limitcode/p/7906447.html

亦可对pkg进行:更新-update,搜索-search,卸载-uninstall,发布-publish。

基本配置命令

npm config list -l:查看npm配置
npm root -g:安装目录,默认 C:Users用户名AppDataRoaming
pm
ode_modules
npm config get cache:缓存目录,默认 C:Users用户名AppDataRoaming
pm-cache
npm config get prefix:默认 C:Users用户名AppDataRoaming
pm

默认占用 C盘资源,可重置缓存路径

  • 预建文件夹,复制现有文件进去
  • 更新路径npm config set prefix "F: odejs pm" npm config set cache "F: odejs pm-cache"
  • 设置环境变量:分别在Path中添加 ;F: odejs pm;

注意,自定义的cnpm也要同步修改。最后可以查看更新后的npm信息

cmd path
cmd where npm

具体参见:https://www.jianshu.com/p/4da509245933

其他

npm set registry https://registry.npm.taobao.org  # 注册淘宝镜像代理
npm install -g cnpm --registry=https://registry.npm.taobao.org  # 安装cnpm

package.json 

模块根目录下,用于定义包的属性以及项目依赖,通过 npm install 安装

  • main:指定程序主入口文件,默认index.js

React Devtools

支持在浏览器的开发者工具中检查 React组件树,任何组件中的 props(属性) 和 state(状态)。

安装方法参见:

create-react-app 

使用前的准备

1. 安装 Node.js,会同时安装 npm
2. npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org

create-react-app 来自于 Facebook,通过该命令,无需配置即可快速构建 React开发环境。

由 create-react-app自动创建的项目基于 Webpack + ES6 

npm install -g create-react-app
create-react-app my-app
cd my-app
npm start

项目创建成功后,若要暴露出项目的webpack配置文件,运行 npm run eject 

env.js:读取env配置文件并将env的配置信息给到全局变量process.env
path.js:提供项目文件的各种路径
webpackDevServer.config.js:小型的Node.js Express服务器
webpack.config.js:webpack配置文件
serviceWorker.js:后台进程脚本,实现离线缓存、消息推送、网络代理(请求转发、伪造响应)等,chrome://serviceworker-internals/ 查看浏览器的Service Worker信息

关于.env的介绍,参见:.env files | github

What other .env files can be used?

  • .env: Default.
  • .env.local: Local overrides. This file is loaded for all environments except test.
  • .env.development.env.test.env.production: Environment-specific settings.
  • .env.development.local.env.test.local.env.production.local: Local overrides of environment-specific settings.

Files on the left have more priority than files on the right:

  • npm start.env.development.local.env.development.env.local.env
  • npm run build.env.production.local.env.production.env.local.env
  • npm test.env.test.local.env.test.env (note .env.local is missing)

创建项目时,若出现如下报错

error code EACCES
error errno EACCES
error FetchError: request to https://registry.npmjs.com/cra-template failed, reason: connect EACCES 104.16.27.35:443
error     at ClientRequest.req.on.err (F:
odejs
pm
ode_modules
pm
ode_modules
ode-fetch-npmsrcindex.js:68:14)

通常是npm库地址有问题,重新配置即可。

原文地址:https://www.cnblogs.com/wjcx-sqh/p/9308550.html