今天我們使用Babel來制作并且發(fā)布一個簡單的npm包
-
首先在terminal中運行命令
npm init,按照提示一步步輸入,如果像我這樣比較懶的話,也可以一直選默認(rèn)值,最后生成了package文件,是這樣的{ "name": "es6-test", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "MIT" } -
接下來我們新建一個入口文件,
touch index.js,寫入module.exports = function({percent = 100, amount}) { const percentOff = (percent / 100) * amount; return percentOff; }Tips:在這里使用
module.exports而不是ES6 export statement的原因是,希望ES5的用戶也能夠不需任何多余的工作就可以使用這個包。 -
如果現(xiàn)在直接發(fā)布的話,這個包是無法工作的,因為我們使用了ES6的feature,所以就需要Babel來幫忙啦,安裝Babel
npm install --save-dev babel-cli@6 babel-preset-es2015@6 -
把Babel的預(yù)處理命令假如我們的
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",為發(fā)布做準(zhǔn)備。 最后運行
npm publish,填上你的username,發(fā)布了,當(dāng)然,你首先得注冊個npm的developer賬號。這樣就可以通過npm install es6-test來安裝你的包了。-
運行結(jié)果
> 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/