babel插件入门

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}`
        );
      }
    }
  }
}
原文地址:https://www.cnblogs.com/mengff/p/12827257.html