1.新增一个文件supto,然后到文件里面,执行git init命令,创建一个package.json文件。
package.json的内容如下:
{
"name": "supto",
"version": "1.0.3",
"description": "surper tool",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"前端常用方法封装"
],
"author": "hyhweb",
"license": "ISC"
}
2.目录结构如下:
3.在根目录下新建index.js文件,在文件里面编写包的功能,把方法和属性暴露出来。例如:
编写一个操作cookie的依赖包或者插件。内容如下:
export const cookie = {
set(name, value) {
let Days = 30
let exp = new Date()
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString()
},
get(name) {
let arr, reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
if (arr = document.cookie.match(reg)) { return unescape(arr[2]) } else { return '' }
},
del(name) {
let exp = new Date()
exp.setTime(exp.getTime() - 1)
let cval = this.get(name)
if (cval != '') { document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString() }
}
}
4.登录npm和发布包:
npm login
npm publish
5.查看发布后的包:https://www.npmjs.com/package/supto