Npm-related npm initialization, switching npm mirror source, package.json interpretation, require loading mechanism & ES6 downgrade processing - babel package

Npm-related npm initialization, switching npm mirror source, package.json interpretation, require loading mechanism & ES6 downgrade processing - babel package

1. npm-related

1.1 What has been learned

npm (node ​​package manager) is a node package manager, we have learned to install and uninstall packages before,** the first timelocal**Installation needs to be initialized first.

initialization:

npm init -y
npm init --yes
npm init

Global installation:

The global installation is generally a command. After the global installation, this command can be used in any folder.

Things installed globally cannot be loaded by require

# 安装命令
npm i 包名 -g
npm install 包名 -g
# 卸载命令
npm un 包名 -g
npm uninstall 包名 -g

Local installation:

# 安装命令
npm i 包名
npm install 包名
# 卸载命令
npm un 包名
npm uninstall 包名

1.2 Supplement on installing third-party packages

  • Install third-party packages

    # 老版本的node安装,后面加 --save,是为了把安装的第三方模块在package.json中做记录,新版不用
    npm install 包名 --save
    # 正常的安装
    npm install 包名
    # 一次安装多个包,名字之间用空格隔开
    npm install 包名1 包名2 包名3
    npm i express mysql art-template
    # 指定包的版本进行安装
    npm install 包名@版本号
    # 简写
    npm i 包名
    
  • Install packages from the cache directory

    # 查看缓存目录
    npm config get cache
    # 从缓存目录下载包
    # --cache-min 后面跟的是时间,单位是分钟,超过这个时间才去服务器下载
    npm install 包名 --cache-min 9999999
    
  • View the global installation directory

    # 查看全局安装时的安装目录
    npm root -g
    

1.3 Switch npm mirror source

  • The server where npm stores package files is abroad, and the speed is very slow, so we need to solve this problem.

  • The domestic Taobao development team has made a backup of npm in China, and the URL is: http://npm.taobao.org/.

    # 查看当前的源
    npm config ls
    # 在上面命令的结果有,有下面一行,该行记录的网站就是我们安装第三方模块的网站
    # registry = "https://registry.npmjs.org/"
    
    # 下载包的时候切换源
    npm install express --registry=https://registry.npm.taobao.org
    # 全局设置
    npm config set registry https://registry.npm.taobao.org
    # 原始的路径
    # https://registry.npmjs.org/
    # nrm 是管理镜像源的模块,通过nrm来管理镜像源
    npm i nrm # 自行查询如何使用 
    

1.4 package.json

After initialization, a package.json file will be generated

  • createpackage.json

    npm init 
    npm init -y
    
  • main

    The main field specifies the loaded entry file

  • dependencies dependencies (plural)

    • Specifies the packages that the current project depends on (requires)
    • Software version number [email protected]
      1. Major version. Minor version. Minor version
      2. Minor version : When the project undergoes partial modification or bug correction, the revised version number will be increased by 1
      3. Minor version : When the project adds some functions on the original basis, the main version number remains unchanged, and the sub-version number is increased by 1
      4. Major version : When the project undergoes major revisions or accumulates a lot of partial corrections, resulting in global changes to the project as a whole, the major version number will be incremented by 1
    "dependencies": {
          
          
        "art-template": "^4.14.2",
        "body-parser": "^1.18.3",
        "express": "^4.16.4",
        "express-art-template": "^1.0.1"
     }
    
    • dependenciesThe field specifies the modules that the project depends on to run
    • npm installAll dependencies can be installed using
    • Each member of the object consists of the module name and the corresponding version requirements, indicating the dependent modules and their version range.
      • Specified version : For example 1.2.2, following the format of "major version. Minor version. Minor version", only the specified version will be installed during installation.
      • Tilde (tilde) + specified version : For example ~1.2.2, it means to install the latest version of 1.2.x (not lower than 1.2.2), but not to install 1.3.x, which means that the major version number and minor version number will not be changed during installation .
      • Caret (caret) + specified version : For example, ˆ1.2.2 means to install the latest version of 1.xx (not lower than 1.2.2), but not to install 2.xx
  • scripts

    scriptsSpecifies the npm command line abbreviation for running script commands, for example, start specifies npm run startthe command to be executed when running.

    "scripts": {
          
          
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node app.js",
        "t": "dir c:\\"
     }
    

    runscripts

    npm run t
    npm run start
    # 只有 start 可以简化调用
    npm start
    
    

The role of dependence:

  • Document the required packages for the project
  • When sending to others, there is no need to send relatively large node_modulesfolders . Just send package.jsonit , you just need to execute npm installto install all the packages

custom command

insert image description here

1.5 A mysterious folder node_modules

  • When we download a third-party package, we will automatically put the downloaded third-party package node_modulesin . directly when using third-party packages require('第三方包的名字').

  • The package we wrote ourselves can also be placed in this folder, just write the package name directly when loading .

  • requireload order of

    • print module object

    • The process of package loading, module.pathsaccording the path in the search step by step

insert image description here

  • require()After loading for the first time , the module/package will be cached , and loaded directly from the cache the require()next time.

1.6 require loading mechanism

  • requirePrioritize loading of modules in the cache
  • If there is no module in the cache, the core module (modules that come with node, such as fs, path, http) will be loaded first , and cached
  • If there is a relative path , the file module is loaded according to the path and cached
    • require('./main')When the extension is omitted
    • Load first main.js, if not load again main.json, if not load again main.node(module written in c/c++)
  • If it is not a file module or a core module, load a third-party module (a module installed by npm)
  • node will look in the node_modules directory (find the directory with the same name as you quoted), for example hererequire('moment')
  • If momenta directory , the module is loaded and cached
  • If the process cannot be found, node will find node_modulesthe directory , the rules are the same as above
  • If the root path of the code file has been found and cannot be found, an error will be reported

example

1. Install in npm empty folder

npm init  # 初始化,生成package.json文件和 node_modules 目录文件夹

2. In the node_modules file directory, a folder is a package file

insert image description here

3. Print package file data in app.js

insert image description here

app.js original file

npm/app.js

// 它会去node_modules/mysql里面找index.js ,因为package.json中规定了入口文件是index.js
const mysql = require('mysql'); 

const db = require('./db');

// 导入自己的文件模块
// const db = require('db'); // 不加 ./ 就会报错
// console.log(db.aa);

// const aaaa = require('aaaa');
// console.log(aaaa.abcd);

npm/db.js

module.exports = {
    
    
    aa: 123
}

npm/package.json

{
    
    
  "name": "abcd",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1",
    "abc": "node app.js",
    "qh": "npm config set registry https://registry.npm.taobao.org",
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    
    
    "jquery": "^2.2.4",
    "mysql": "^2.17.1"
  }
}

2. ES6 downgrade processing

Because ES 6 has browser compatibility issues, some tools can be used for downgrade processing, such as: babel

  • Steps to downgrade the use of babel

    1. Install Node.js
    2. Install babel on the command line
    3. configuration file.babelrc
    4. run
  • Project initialization (the project folder cannot have Chinese)

    npm init -y
    
  • On the command line, install babel babel official website

    npm install  @babel/core @babel/cli @babel/preset-env
    
  • Configuration file .babelrc(create this file manually)

    babel's downgrade configuration

    {
          
          
      "presets": ["@babel/preset-env"]
    }
    
  • From the command line, run

    # 把转换的结果输出到指定的文件
    npx babel index.js -o test.js
    # 把转换的结果输出到指定的目录
    npx babel 包含有js的原目录 -d 转换后的新目录
    

Example 1 - Converting a file

insert image description here

the code

1. File 1.js before conversion

let fn = x => x * x;

let a = 11;
let b = 22;
let c = {
    
    
    a,
    b
}

2. Conversion command

npx babel 1.js -o 2.js

3. Newly generated file 2.js after conversion

"use strict";

var fn = function fn(x) {
    
    
  return x * x;
};

var a = 11;
var b = 22;
var c = {
    
    
  a: a,
  b: b
};

Example 2 - Convert Folder

insert image description here

the code

1. The contents of the a.js file and b.js file in the original js folder are as follows

let fn = x => x * x;

let a = 11;
let b = 22;
let c = {
    
    
    a,
    b
}

2. Convert folder command

npx babel js -d js1

3. Convert the newly generated js1 folder

The contents of the a.js and b.js files in the js1 folder are as follows

"use strict";

var fn = function fn(x) {
    
    
  return x * x;
};

var a = 11;
var b = 22;
var c = {
    
    
  a: a,
  b: b
};

Guess you like

Origin blog.csdn.net/weixin_44867717/article/details/130234372