当前位置:网站首页>Npm+ module loading mechanism

Npm+ module loading mechanism

2022-07-25 23:20:00 081&33

npm With bag

package

package

  • Node.js Medium Third-party module Also known as package
  • Like computers and computers , It's just a different name

Source of package

  • The bag is made by Third party individuals perhaps The team Developed
  • node.js The packages in are free and open source Of , You can use it without paying

Why do you need a bag

  • node.js Of Built-in module Only some Simple built-in API, Development efficiency very low , be based on Encapsulation of built-in modules , Provides a more advanced , More convenient API, It greatly improves the efficiency of development

Where to download the package

  • http://www.npmjs.com/( Search package )— A foreign family IT company , be called npm.Inc
  • http://registry.npmjs.org/( Download package

npm

npm First experience – The traditional way of formatting time

  • Ideas : Format time , Is to create a time object first , Pass this time object , Or directly use each function to extract the corresponding time , Zero complementing function , Just send it out
  • file 1
// How to define the formatting time  function dataformat(dtstr){
    
    const dt = new Date();
  
     console.log(dt) const y = dt.getFullYear() console.log(y) const m = padzero(dt.getMonth()+1) console.log(m) const d = padzero(dt.getDate()) console.log(d) const hh = padzero(dt.getHours()) const mm = padzero(dt.getMinutes()) const ss = padzero(dt.getSeconds()) return `${
    y}-${
    m}-${
    d}  ${
    hh}:${
    mm}:${
    ss}`
}

// Define the zero complement function  function padzero(n){
    
    return n>9 ? n: '0'+n;
}

module.exports = {
    
    dataformat
}
  • file 2
// call 
const TIME = require('./1. How to define the formatting time ') 

const dt = new Date()
console.log(dt)

const res = TIME.dataformat(dt);
console.log(res)

 Insert picture description here

npm First experience – Advanced practice of formatting time

Installing packages in a project
  • Use npm install The name of the complete package
  • Shorthand way npm i The name of the complete package

 Insert picture description here

//1  Install the package needed  npm install moment / npm i moment
//2  Import the required package 
const moment = require('moment')
//3  lookup API How to use the document is in the previous website. Go in and use Baidu to open , It opens at Documentation View the specific writing method , call moment Method 
const TIME = moment().format('YYYY-MM-DD HH:mm:ss')
console.log(TIME)

 Insert picture description here

What's more after installing the package

 Insert picture description here
Generated in project package.json and package-lock-json The difference between the two

  • package-lock.json It will be npm change node_modules Directory tree perhaps package.json Automatically generated when , When we're in npm install When installing a package , Will generate , It stores some information of the project and the modules it depends on ,
  • package-lock.json The meaning of existence is to lock the version , As long as we are different package.json, He won't change
  • For example : Suppose we have installed vue, When we run the installation npm install vue -save When , In the project package.json Of vue The version is vue: ^3.0.0, Our computer is installed with vue The version is 3.0.0 edition , After we submit the project code , After a while ,vue New version released 3.0.1, Then a new colleague came , From the new git clone Cloning project , perform npm install During installation , On his computer vue The version is 3.0.1 了 , because ^ Just locked the main version , In this way, in our computer vue The version will be different , In theory ( If everyone follows semantic version control ), They should still be compatible , But maybe bugfix It will affect the functions we are using , And when using vue edition 3.0.0 and 3.0.1 Runtime , Our application will produce different results .
  • We can think of locking the version number , But you can only lock and control your own project version number , What about the dependent packages in your project ? How do you control and restrict others to lock the version number ?
  • All have package-lock.json, When we next npm install When ,npm It is found that if there is package-lock.json file , Will be based on package-lock.json To process and install dependencies based on the contents of the package.json, In this way, the same results will appear in each installation . No matter what machine you install it on or when
  • Be careful , Use cnpm install When , It doesn't generate package-lock.json file , Nor will it be based on package-lock.json To install dependent packages , Still use package.json To install .
Install the latest version of the package
  • By default , We use npm install install is The latest version My bag
  • Want to install the latest version of the package , We can use npm install [email protected] To install , During the new installation , We There is no need to delete the original package
Semantic version specification of package
 Defined in dotted decimal form , There are three digits , for example :2.24.1
 First digit : The big version , The bottom layer has changed, and this number has changed , Destructive 
 Second digit : Feature version , Added some new features , Non destructive 
 Third digit :bug Fix version , Fixed some bug, Non destructive 

 Rules for version number promotion : As long as the previous version number is upgraded , The following version number is set to zero 

Package management profile

  • package.json, Record some Configuration information related to the project
  • name , Version number , describe , Those bags , Those are only used during development , Those are used during development and deployment

Further understanding package.json Configuration file for

  • In project development , Sometimes we Very little code is actually written , however node_modules The code is big It is not conducive to sharing source code among teams , These packages can be downloaded online , When sharing code between teams Need to get rid of node_modules, But how do team members know there is What kind of package Well , Need us to package.json It's written clearly Yes
  • Later in the development process , We need to node_modules Add to .gitignore Ignore files

Quick creation package-json file

npm init -y

Be careful

  • The above order Can not run stay Chinese catalog , perhaps The directory has spaces
  • In execution npm install When , Will bring us Name and version number of the installation package **** Automatically Add to package.json file in

dependencies

  • stay package.json In file , There is one dependencies node , It is specially used to record US Installed those packages , And package version
  • If we use npm install to want to Install multiple packages at a time When , Between Separate with spaces

Install all packages at once

npm install
npm i
  • If we Deleted node_modules, When we run the program , will Report an error due to lack of package , Now we need install The required All bags , Use npm install perhaps npm i
  • When the order is executed , Will read package.json In the document dependencies node , Read The node and version number of the corresponding package after , Download the package at one time Into our project

Uninstall package

npm uninstall  name  
 This is not abbreviated 
  • After the command is executed successfully , Will package.json In file dependencies In nodes Corresponding package name and version Also deleted

devdependencies

  • Some bags are only The development phase uses , It will not be used after online , It is suggested to add these packages to devdependencies
  • Corresponding , If some packages are in Both development and online are needed , Installed in dependencies
 Specific operation method :--save-dev You can change the order of names with the installation package 
 Use npm install moment( The name of the installation package ) --save-dev
npm install moment -D

Tips

  • Want to know if this package will be used in development , We can do that in the above website Open it with Baidu , Search this package , Click in The installation tutorial includes

Why is the speed of unpacking slow

  • We need to download the package from Foreign servers up and down , The transmission of network data needs to go through Long submarine optical cables Spread to China , And the seafloor The number of optical cables is small , So speed Very slowly

terms of settlement

TaoBao npm Mirror image The server

  • Mirror image : It's a kind of File storage , copy
     Insert picture description here

Switch npm The next package image source

  • The image source of the next package , refer to The server address of the package
 View the current package image source 
npm config get registry
 Switch the image source of the next package to the image source of Taobao 
npm config set registry=https://registry.npm.taobao.org/
 View the current package image source 
npm config get registry

nrm

  • in order to It is more convenient to switch the image source of the next package , We provide nrm This gadget , utilize nrm This terminal command , You can quickly switch and view the image source
 install nrm
npm i nrm -g
 View all image sources 
nrm ls
 Switch image source 
nrm use taobao

Classification of packages

  • There are two types of subcontracting : Project package ; Global package

Project package

  • Installed to node_modules The package in is called Project package
 Project packages fall into two categories 
-  Development depends on the package : Only used during development , Installed to devDependencies In the package 
-  Core dependency package : Packages used after development and launch , Installed to dependencies In the package 

 These two packages are installed in different ways , One needs to add -D perhaps --save-dev, The other is directly related to the name 

Global package

  • In execution npm install when , If we Provides -g Parameters , This package is called Global package
  • The storage path of the global package defaults to :C:\Users\w5339\AppData\Roaming\npm\node_modules
  • When finding the path ,AppData Probably hide 了 , Click on see , Just cancel
 Globally install the specified package 
npm install moment -g
 Delete the specified package globally 
npm uninstall moment -g

Be careful

  • Only Tool nature package , Global installation is necessary
  • If you don't know Whether global installation is required , We can also talk about the one above website Search inside Official documents

i5ting_toc

i5ting_toc It is a will. md File conversion to html Page gadgets 

 take i5ting_toc Install as a global package 
npm install -g i5ting_toc
 call i5ting_toc Easily md File conversion to html file 
i5ting_toc -f  File path to be converted  -o

Standardized package structure

  • A standardized package , Must meet the following Three requirements
1. Packages must exist as separate directories 
2. The top-level directory of the package must contain package.json This package manages the configuration file 
3.package.json Must include name,version,main These three attributes , Each represents the name of the package , Version number , The entrance to the bag 
 When we are from require When you import it , I will go node_modules Next, find the package file below package.json file , Then find the main, Find the corresponding file according to this path 

Develop your own package

Three functions

  • Format date
  • escape HTML Medium Special characters
  • Restore HTML Medium Special characters

The basic structure of the initialization package

  • 1. Create a new one xx-tools, As the root directory of the package
  • In this file , Create three new files
    • package.json— package Manage profiles
    • index.js– Package entry file
    • README.md– Bag documentation

initialization package.json

{
    
    "name":"xx-tools",
    "version":"1.0.0",
    // Export found main, file found 
    "main":"index.js",
    "description": " Provides formatting time ,HTMLEscape Related functions ",
    "keywords": ["xx","dataFormat","eacape"],
    // Open source license agreement 
    "license":"ISC"
}

Split different functions

 Insert picture description here

  • root directory
     Insert picture description here
  • dataformat.js htmlescape only Create two files Cut the code into it , And then use module.exports Export function that will do
  • index.js Separate the two files Import after , stay export , Because when you look for documents, you find package.json, Find the inside main, Then find the corresponding file , So you must import the file into index.js in , Then export .

index.js Code


const dataformat = require('./src/dataformat') const htmlEscape = require('./src/htmlescape') //es6 The expansion operator of , Expand the object and save it to another object , We are going to return the whole function , Instead of returning a value , So use the expansion operator  == I don't quite understand why I want to take out the content and put it into a new object , But not before == module.exports = {
    
    ...dataformat,
    ...htmlEscape
}

  • It is equivalent to taking out the contents and putting them into a new object
 let bar = {
     a: 1, b: 2 }; let baz = {
     ...bar }; // {
     a: 1, b: 2 }

Write instructions for the package

 Insert picture description here
 Insert picture description here


Release package

  • On the official website register npm account number
  • Sign in npm account number , But this login is in Terminal login Of , We need to enter commands at the terminal npm login, Then enter the user name in turn , password , mail , Log in , But notice , This has to be npm Official server Next to , It will fail under the Taobao image , have access to nrm cls To view the , And then use nrm use npm Switch
  • Release package , When publishing, the name of the package cannot be repeated with the existing one , We first Check on the official website Ask if you have the same bag , Then we switch to the package Under the root directory ( namely xx-tools below ), function npm publish, When it's done , We can do it in Log in to our account on the official website , Click on your own Head portrait , Point to package Inside , There is the package we released

Delete published packages

  • function **npm unpublish Package name --force,** You can delete the packages we have released
    • npm unpublish Orders can only Delete 72 Within hours Published packages
    • npm unpublish Deleted package , stay 24 Repeated publishing is not allowed within hours
    • Try to be careful when releasing packages , Try not to publish meaningless packages

Module loading mechanism

Load from cache first

  • After the module is loaded for the first time Will be cached , It also means that Multiple calls require() It's only going to be executed once . Inside a document is a print ok Of , Call it three times in another file , Only one... Will be printed ok( No matter which built-in module , User defined module , Third party modules , Will be loaded from the cache first , thus Improve the loading efficiency of the module

The loading mechanism of built-in modules

  • Built-in module Of Load priority is highest
  • There are two in our project fs, One is built-in fs modular , The other one is downloaded by our third party fs modular , But to perform require(‘fs’) Throughout What is returned is the built-in module fs

Custom module loading mechanism

  • Use require() When loading a custom module , Must specify With ./ perhaps …/ The path identifier at the beginning , When loading, if Is not specified , be node I'll think of it as Built in modules or third-party modules to load
  • In the use of require() When importing custom modules , If The extension of the file is omitted , be node.js You will try to load the files in the following order
1. Load by exact file name 
2. completion .js File name to load 
3. completion .json Extension to load 
4. completion .node Extension to load 
5. Loading failed , The terminal reported an error 

Loading mechanism of third-party modules

  • Node.js From Parent directory of the current module Start , Try from **/node_modules Folder Load in Third-party module **, If the corresponding third-party module is not found , Then move to In the parent directory of the upper layer , Loading , Up to the root directory of the file

 Insert picture description here

Catalog ( Folder ) As a module

  • stay json Single quotation marks cannot be used in
  • When one Folder Directory as identifier , Pass to require() When loading , Yes Three loading methods
  • Find a directory called... Under the loaded directory package.json The file of , seek main attribute , As require() Loaded entrance
  • If in the directory No, package.json file , perhaps main entrance non-existent perhaps Unable to resolve , be node.js Will try to load... In the directory index.js file
  • If The above two steps all Failure 了 , be node.js Error messages will be printed on the terminal , Missing report module ERROR:can not find module ‘xxx’
原网站

版权声明
本文为[081&33]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/206/202207252311341248.html