vuejs 插件开发并发布到npm--(2)js插件开发

一、以日期格式转化函数插件开发为例

1、生成项目文件夹formateDate;

2、在formateDate文件夹下生成index.js文件,并执行npm init生成package.json文件;

3、在formateDate文件夹下生产lib文件夹,用于进行插件开发;

4、在lib文件夹下新建formateDate.js并进行开发。

index.js

var formateDate = require('./lib/formateDate.js');

module.exports = {
    dateFMT: formateDate.dateFMT
}

package.json

{
  "name": "hyy-formatedate",
  "version": "1.0.0",
  "description": "simple formatedate",
  "main": "index.js",
  "scripts": {
    "watch": "mocha --watch tests/",
    "test": "mocha --reporter spec --timeout 2000 --recursive tests/",
    "test-cov": "istanbul cover ./node_modules/mocha/bin/_mocha -- -t 2000 --recursive  -R spec tests/",
    "test-html": "mocha --reporter mochawesome tests/"
  },
  "bin": {
    "formateDate": "./bin/formateDate.js"
  },
  "keywords": [
    "formateDate"
  ],
  "author": "yyhu",
  "license": "MIT",
  "devDependencies": {
    "chai": "^3.5.0",
    "istanbul": "^0.4.1",
    "mocha": "^2.3.4",
    "mochawesome": "^1.2.1"
  }
}

formateDate.js

module.exports = {
    /**
     * @param date formate
     */
    dateFMT: function (date, fmt) {
        var o = {
            "M+": date.getMonth() + 1,               //月份   
            "d+": date.getDate(),                    //
            "H+": date.getHours(),                   //小时   
            "m+": date.getMinutes(),                 //
            "s+": date.getSeconds(),                 //
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
            "S": date.getMilliseconds()             //毫秒   
        };
        if (/(y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            }
        }
        return fmt;  
    }
}

二、测试

1、放到具体项目里,借助浏览器环境进行测试;

2、单元测试----借助单元测试工具;

三、发布

1、去npm官网申请账号;

2、在formateDate文件夹下执行npm adduser----用户名、密码、邮箱;

3、在formateDate文件夹下执行npm publish发布开发好的插件包。

四、如何使用已经发布出去的包?

1、在具体的项目中添加依赖:npm i hyy-formatedate --save;

2、import formatedate from 'hyy-formatedate';

3、使用formatedate.dateFMT(date, fmt);

猜你喜欢

转载自www.cnblogs.com/TiffanyHYY/p/10364728.html
今日推荐