当前位置:网站首页>Teach you how to develop your own NPM package (publish to the NPM official website)
Teach you how to develop your own NPM package (publish to the NPM official website)
2022-06-29 06:20:00 【Concision.】
Develop your own npm package
1. Standardized package structure
A standardized package , Its composition structure , Must meet the following 3 Point requirements :
- Package must be in Separate directories And exist
- The top-level directory of the package must contain
package.jsonThis package manages the configuration file package.jsonMust includename,version,mainThese three attributes , Each represents the name of the package 、 Version number 、 The entrance to the bag . The entry file of the package refers to that we userequireFile actually imported when using the .
2. Develop your own package
2.1 Package function
① Format date
② escape HTML Special character in
③ Restore HTML Special character in
2.2 The basic structure of the package
- newly build
JoneytoolFolder , As The root of the package - stay
JoneytoolIn the folder , Create the following structure , These include package.json ( Package management profile )、index.js ( Package entry file )、README.md ( Documentation of the package )、src.
2.3 Code
dateFormat.js
// A function that defines the formatting time
function dateFormat(dateStr) {
const dt = new Date(dateStr)
const y = dt.getFullYear()
const m = padZero(dt.getMonth() + 1)
const d = padZero(dt.getDate())
const hh = padZero(dt.getHours())
const mm = padZero(dt.getMinutes())
const ss = padZero(dt.getSeconds())
return `${
y}-${
m}-${
d} ${
hh}:${
mm}:${
ss}`
}
// Define a function that complements zero
function padZero(n) {
return n > 9 ? n : '0' + n
}
module.exports = {
dateFormat
}
htmlEscape.js
// Define escape HTML Character functions
function htmlEscape(htmlstr) {
return htmlstr.replace(/<|>|"|&/g, match => {
switch (match) {
case '<':
return '<'
case '>':
return '>'
case '"':
return '"'
case '&':
return '&'
}
})
}
// Define restore HTML String function
function htmlUnEscape(str) {
return str.replace(/<|>|"|&/g, match => {
switch (match) {
case '<':
return '<'
case '>':
return '>'
case '"':
return '"'
case '&':
return '&'
}
})
}
module.exports = {
htmlEscape,
htmlUnEscape
}
index.js
// This is the package entry file
const date = require('./src/dateFormat')
const escape = require('./src/htmlEscape')
// Expose needed members
module.exports = {
...date,
...escape
}
package.json
package.json It includes 6 Parts of
- The name of the package
name, Be careful The name and of the folder name The name doesn't matter . Check the official website before writing your own package name , Because the package name cannot be repeated . - The version of the package
version, The default from the 1.0.0 Start - Package entry file
main - Package description information
description - Search for keywords
keywords - The open source license agreement that the package complies with
license,npm The official recommendationISC
{
"name": "itheima-tools",
"version": "1.1.0",
"main": "index.js",
"description": " Provides formatting time 、HTMLEscape Related functions ",
"keywords": [
"itheima",
"dateFormat",
"escape"
],
"license": "ISC"
}
README.md
README.md file , It is the instruction document of the package , Convenient for users to refer to .README What is written in the document , There are no mandatory requirements ; As long as the function of the package can be clearly 、 usage 、 Please describe the precautions clearly .
The package we created README.md file in , It will include the following 6 item :
Installation mode 、 Import the way 、 Format time 、 escape HTML Special character in 、 Restore HTML Special character in 、 Open source licenses 

2.4 Release
Registered account
visit https://www.npmjs.com/ Website , Click on sign up Button , Enter the registration user interface , Register your own account .
Sign in npm account number
npm After account registration , Sure In the terminal perform npm login command , Enter user name in sequence 、 password 、 mailbox 、OTP after , You can log in successfully .
Be careful : Running npm login Before the command , You must first switch the server address of the next package to npm The official server of . Otherwise, the login will fail !
Login successful interface 
Release
take terminal Switch to The root of the package after , function npm publish command , You can publish the package to npm On ( Be careful : Package name cannot be the same ).
see
stay npm Official website Log in to your account , Click the down arrow next to the avatar 
choice Packages View your uploaded packages 

2.5 Delete
Carry out orders npm unpublish Package name --force, Can from npm Delete published packages .
Be careful :
① npm unpublish command Delete only 72 Packages released within hours .
② npm unpublish Deleted package , stay 24 Repeated publishing is not allowed within hours .
2.6 Use
Carry out orders npm i joney-tools Download your own package 
Here we import the module , Then use a function that formats the time
const joneytools = require('joney-tools')
const dataStr = joneytools.dateFormat("2020-1-1 10:5:5")
console.log(dataStr);
perform node 2.js, The output is shown in the figure , The time is formatted correctly , The module can be successfully downloaded and used .
边栏推荐
- Devops development, operation and maintenance Basics: using Jenkins to automatically build projects and notify by email
- Are there too many programmers in China at present?
- Call the computer calculator and use it to convert several base numbers
- Agile invincible event
- What are the uses of static?
- Installing modules in pycharm
- 2022.02.15
- Mongodb basic knowledge summary
- Rearrangement string of leetcode simple question
- Meta metauniverse female safety problems occur frequently. How to solve the relevant problems in the metauniverse?
猜你喜欢

Test Development - ten years of sharpening one sword (VII) interface test tool postman

Will the order of where conditions in MySQL affect the union index? Will where 1 =1 affect the use of the index? Does where 1 =1 affect the use of indexes?

Leetcode simple question: judging the color of a grid on a chess board

Why are keys unordered in golang map

Sourcetree remote red exclamation point

Fault: NetBt log for id4321

Pytest (7) -yield and termination function

2022 recommended tire industry research report industry development prospect market analysis white paper

Hyperledger Fabric 2. X custom smart contract

Servlet version conflict causes page 404
随机推荐
What are the uses of final?
Review of MySQL knowledge points
National Defense University project summary
How to insert pseudo code into word documents simply and quickly?
Regular expressions for shell script values
2022 recommended tire industry research report industry development prospect market analysis white paper
Design and practice of kubernetes cluster and application monitoring scheme
Ti Click: quickly set up tidb online laboratory through browser | ti- team interview can be conducted immediately
2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin copper (no2tmpp) Cu) /2-nitro-5,10,15,20-tetra (4-methylphenyl) porphyrin (no2tmpp) H2) Qiyue porphyrin supply
51 lines of code, self-made TX to MySQL software!
Openfpga wishes you a happy Lantern Festival!
Hyperledger Fabric 2. X custom smart contract
Honeypot based on MySQL load data local INFILE
[deep learning] - maze task learning I (to realize the random movement of agents)
Meso tetra (4-N, N, n-trimethylaminophenyl) porphyrin (ttmapp) /meso tetra - [4- (BOC threonine) aminophenyl] porphyrin (TAPP thr BOC) supplied by Qiyue
64 commonly used terms for data analysis, really all!
Servlet version conflict causes page 404
[high concurrency] deeply analyze the callable interface
2022.02.14 - 239. A single element in an ordered array
Personal blog item: processing of reading number +1 after viewing article details