开发属于自己的包

创建index.js 文件里面的内容为:

// index.js文件

// 包的入口文件

const date = require('./src/dataFormat')
const escape = require('./src/htmlEscape')
// 向外暴露需要的成员
module.exports = {
    ...date,
    ...escape
  }
 

创建package.json文件 里面的内容为:

{
    "name": "it_date_tools",
    "version": "1.0.0",
    "main": "index.js",
    "description": "提供了格式化时间和HTMLEscape功能",
    "keywords": [
        "lllll",
        "dateformat",
        "escape"
    ],
    "license": "ISC"
}
 
创建README.md文件 里面的内容为:

### 安装
```
npm i lllll_tools
```

### 导入
```js
const itheima = require('./lllll_tools')
```

### 格式化时间
```js
// 调用 dateFormat 对时间进行格式化
const dtStr = itheima.dateFormat(new Date())
// 结果  2020-04-03 17:20:58
console.log(dtStr)
```

### 转义 HTML 中的特殊字符
```js
// 带转换的 HTML 字符串
const htmlStr = '<h1 title="abc">这是h1标签<span>123&nbsp;</span></h1>'
// 调用 htmlEscape 方法进行转换
const str = itheima.htmlEscape(htmlStr)
// 转换的结果 &lt;h1 title=&quot;abc&quot;&gt;这是h1标签&lt;span&gt;123&amp;nbsp;&lt;/span&gt;&lt;/h1&gt;
console.log(str)
```

### 还原 HTML 中的特殊字符
```js
// 待还原的 HTML 字符串
const str2 = itheima.htmlUnEscape(str)
// 输出的结果 <h1 title="abc">这是h1标签<span>123&nbsp;</span></h1>
console.log(str2)
```

### 开源协议
ISC

创建src文件  里面创建htmlEscape.js文件和dataFormat.js文件两个文件

htmlEscape.js文件内容为:

// htmlEscape.js文件

// 获取与替换
function htmlEscape(htmlstr) {
    return htmlstr.replace(/<|>|"|&/g, (match) => {
        switch (match) {
            case '<':
                return'&lt;'
            case '>':
                return'&gt;'
            case '"':
                return'&quot;'
            case '&':
                return'&amp;'
        }
    })
}

function htmlUnEscape(str) {
    str.replace(/&lt;|&gt;|&quot;|&amp;/g, (match) => {
        switch (match) {
            case '&lt;':
                return'<'
            case '&gt;':
                return'>'
            case '&quot;':
                return'"'
            case '&amp;':
                return'&'
        }
    })
}

// 调用
module.exports = {
    htmlEscape,
    htmlUnEscape

}
 

dataFormat.js文件内容为:

// dataFormat.js文件

// 定义格式化时间的函数
function 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}`
}


  // 定义一个补零的函数
function padZero (n) {
    return n > 9 ? n : '0' + n
}


// 调用
module.exports = {
    dateFormat,

}
原文地址:https://www.cnblogs.com/lblblibin/p/13546738.html