如何编写 gulp 插件

  Vanessa

1.  编写 package.json

注意填写 name, version, main, description, keywords, dependencies 

可参见 https://github.com/Vanessa219/gulp-header-license/blob/master/package.json

{
  "name": "gulp-header-license",
  "version": "1.0.0",
  "description": "Gulp extension to add license to file(s) in the pipeline.",
  "main": "./index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git://github.com/Vanessa219/gulp-header-license.git"
  },
  "keywords": [
    "header",
    "license",
    "gulpplugin"
  ],
  "author": "Vanessa <lly219@gmail.com> (http://vanessa.b3log.org)",
  "license": "MIT",
  "bugs": {
    "url": "https://github.com/Vanessa219/gulp-header-license/issues"
  },
  "dependencies": {
    "concat-with-sourcemaps": "*",
    "object-assign": "*",
    "through2": "*"
  },
  "homepage": "https://github.com/Vanessa219/gulp-header-license#readme",
  "maintainers": [
    {
      "name": "Vanessa",
      "email": "lly219@gmail.com"
    }
  ]

 

2. 编写 index.js

基础:BufferStream

可参见:https://github.com/Vanessa219/gulp-header-license/blob/master/index.js

module.exports = function (template, config) {

    return through.obj(function (file, enc, cb) {
        // fils is exit
        if (file.isNull()) {
            this.push(file);
            return cb();
        }

        // process file
        if (file.isBuffer()) {
            file.contents = Buffer.concat([prefixText, file.contents]);
        }
        if (file.isStream()) {
            file.contents = file.contents.pipe(prefixStream(prefixText));
        }

        // do something

        // for pipe
        this.push(file);
        cb();
    });
};

 

3. 注册 npmjs

 https://www.npmjs.com/

4. 添加用户信息

npm adduser
npm login

5. 发布

npm publish

啦啦啦,不要重名,此时,你就可以看到你的插件上传上去了

https://www.npmjs.com/package/gulp-header-license

6. update

更新 package.json 中的 version, `npm publish`

 

具体实现可参见 :gulp-header-license


欢迎加入开源技术 Q 群 242561391 B3log,加入黑客派,让学习和分享成为一种习惯!