Getting Started with Node.js - npm and Packages

1 Introduction

The content of this article comes from bilibili dark horse programmers

2 bags

2.1 What is a package

Third-party modules in Node.js, also known as packages
Search for the packages you need from the website https://www.npmjs.com/
Download the packages you need from the server at https://registry.npmjs.org/

2.2 Standard package structure

  1. Must exist as a separate directory
  2. The package management configuration file package.json must be included in the top-level directory
  3. package.json must contain three attributes: name (package name), version (version number), main (entry file)

3 New package

  1. Create a new folder itheima-test
  2. New package.json
    Create new package.json under itheima-test folder
{
    
    
  "name": "itheima-test", // 名称自定义
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "description": "提供了格式化时间等功能",
  "keywords": ["dateFormat"],
  "license": "ISC"
}
  1. Create a new README.md
    under the itheima-test file and create a new README.md
## 安装
npm install itheima-test

## 导入方式
import format from 'itheima-test'

## 格式化时间
const dtStr = format.dateFormat(new Date) // 2022-12-18 16:45:34

## 开源协议
ISC
  1. Create new index.js
    Create new index.js under itheima-test folder
// 这是包的入口文件
import format from "./src/dateFormat.js";

export default {
    
    
  ...format
}
  1. Create new dateFormat.js
    Create a new src folder under the itheima-test folder, and create a new dateFormat.js under the src folder
const padZero = (n) => {
    
    
  return n < 10 ? `0${
      
      n}` : n
}

// 定义时间格式化方法
const dateFormat = (dateStr) =>{
    
    
 const dt = new Date(dateStr)
 const y = padZero(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}`
}

export default {
    
    
  padZero,
  dateFormat
}

4 release package

If you do not have an npm account, you need to visit https://registry.npmjs.org/ to register one

// 登录 npm
npm login
// 发布包
npm publish
// 删除包
npm unpublish 包名 --force

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/128661033