1. 插件目錄結構
src
|----index.js
babel-plugin-test
|----index.js
js
.babelrc(可選)
package.json
2. 插件調試
在本目錄下安裝babel-cli,或者全局安裝babel-cli
npm babel-cli -D
本目錄安裝,不能直接在shell中調用babel命令,需要放在package.json的script命令里面,全局安裝的可以在shell中執行babel命令。
babel src/ -d js/ --plugins babel-plugin-test //命令將src下的文件,經過babel-plugin-test下的plugin轉換,輸出到js目錄下
也可以在目錄下添加.babelrc文件,在里面指定plugin,就不用添加--plugins參數了
{ "plugins": [ [ "./babel-plugin-test", { "libraryName": "mlib", "styleLibraryName": "theme-me" } ] ] }
3. 插件示例
3.1 實現一個基礎的按需加載轉換的例子
import { Button, Loading } from 'mlib'
轉換為
import Button from 'mlib/lib/Button';
import Loading from 'mlib/lib/Loading';
plugin的index.js
module.exports = function({types: t}) { return { name: 'babel-plugin-loadDemand', visitor: { ImportDeclaration(path, {opts}) { const { node: { specifiers, source } } = path //只有配置中的指定lib,才進行轉換,這里是.babelrc中的m-lib if (source.value === opts.libraryName) { const arr = specifiers.map(specifier => ( t.importDeclaration( [t.ImportDefaultSpecifier(specifier.local)], // 拼接詳細路徑 t.stringLiteral(`${source.value}/lib/${specifier.local.name}`) ) )) path.replaceWithMultiple(arr) } } } } }
這里只對簡單的情況進行了處理,對於
//使用as import { Button as btn, Loading } from 'm-lib' //全量引入,再調用 import mlib from 'mlib' mlib.Button
這兩種情況都沒有處理,要得到更完備的效果,需要更多的工作。
可以參考babel-plugin-lodash, babel-plugin-ramda, babel-plugin-component。
3.2 實現一個處理debugger的例子
在開發環境輸出debugger的行和列,在生產環境刪除debugger。
module.exports = function() { return { name: 'drop-debugger', visitor: { DebuggerStatement(path, state) { if (process.env.NODE_ENV === 'production') { path.remove(); return; } const { start: { line, column } } = path.node.loc; console.log( `Debugger exists in file: ${ state.filename }, at line ${line}, column: ${column}` ); } } } }