如何使用ES6和Babel制作并发布npm包

2017-04-28  本文已影响1416人  bianer233

今天我们使用Babel来制作并且发布一个简单的npm包

  1. 首先在terminal中运行命令npm init,按照提示一步步输入,如果像我这样比较懒的话,也可以一直选默认值,最后生成了package文件,是这样的

     {
         "name": "es6-test",
         "version": "1.0.0",
         "description": "",
         "main": "index.js",
         "scripts": {
             "test": "echo \"Error: no test specified\" && exit 1"
     },
         "author": "",
         "license": "MIT"
     }
    
  2. 接下来我们新建一个入口文件,touch index.js,写入

     module.exports = function({percent = 100, amount}) {  
         const percentOff = (percent / 100) * amount;
         return percentOff;
     }
    

    Tips:在这里使用module.exports而不是ES6 export statement的原因是,希望ES5的用户也能够不需任何多余的工作就可以使用这个包。

  3. 如果现在直接发布的话,这个包是无法工作的,因为我们使用了ES6的feature,所以就需要Babel来帮忙啦,安装Babel

     npm install --save-dev babel-cli@6 babel-preset-es2015@6  
    
  4. 把Babel的预处理命令假如我们的package.json文件中,像这样

     "scripts": {
         "test": "echo \"Error: no test specified\" && exit 1",
         "build": "babel index.js --presets babel-preset-es2015 --out-dir .",
         "prepublish": "npm run build
     }
    

    同时也加入了 "prepublish": "npm run build",为发布做准备。

  5. 最后运行 npm publish,填上你的username,发布了,当然,你首先得注册个npm的developer账号。这样就可以通过 npm install es6-test 来安装你的包了。

  6. 运行结果

     > var offof = require("es6-test")
     undefined
     > offof({percent:50, amount:500})
       250
    

参考Link: https://booker.codes/how-to-build-and-publish-es6-npm-modules-today-with-babel/

上一篇 下一篇

猜你喜欢

热点阅读