首页 > 其他 > 详细

自制简单的babel插件

时间:2019-06-05 16:41:21      阅读:116      评论:0      收藏:0      [点我收藏+]

示例

一个用于生产时 去掉代码中 所有的打印代码,如 console.log(‘乱七八糟‘)

待转换的文件 test.js

console.log(你好);
let a = as;

babel转换文件  plugin.js

module.exports = function (babel) {

    const { types: t, template } = babel;

    const keyPathVisitor = (node , properties) => {
        let temp = node
        for(let item of properties) {
            if (temp[item])
                temp = temp[item]
            else {
                temp = null
                break
            }
        }
        return temp
    }

    const visitor = {
        //需要访问的节点名
        //访问器默认会被注入两个参数 path(类比成dom),state
        ExpressionStatement(path, state) {
            if (process.env.NODE_ENV === production) {
              const node = path.node;
              //延当前节点向内部访问,判断是否符合console解析出的ast的特征
              const expressionNode = keyPathVisitor(node, [expression]);
              const isCallExpression = expressionNode.type === CallExpression;
              if (isCallExpression) {
                const objectName = keyPathVisitor(expressionNode, [callee, object, name]);
                const prototypeName = keyPathVisitor(expressionNode, [callee, property, name]);
                if (objectName === console && prototypeName === log) {
                  //如果符合上述条件,直接移除该节点
                  path.remove();
                }
              }
            }

        }
    };

    return {
        visitor
    };
};

 

进行转换:

使用babel-cli 进行手动转换,安装  npm i babel-cli -D

1、指定转换文件  npx babel --plugins ./plugin.js test.js。

成功转换

2、用.babelrc 配置 进行转换。

{
  "plugins": [
    "./pluginLog" // babel转换文件所在位置
  ]
}
E:\workspace\babel\test>npx babel test.js

let a = as;

 

写在文末:

所谓的babel插件,就是用来 转换代码。源代码 到 源代码。具体来说 就是 将环境(如浏览器)不识别的代码转换成 能被支持的代码。

如 es2015 (将es6 转换成es5),babel-plugin-compoment (饿了么组件的 按需加载功能)。

任何 代码都可以按照 我们想要的 形式转换(即使转换成为不被识别,有毒 哈哈)。转换的关键是 操作 ast 。

你需要先将 被转换的源代码 解析 出它的 ast结构,然后针对ast进行操作(是个大工程)。

解析出ast结构:https://astexplorer.net/

操作ast:https://github.com/jamiebuilds/babel-handbook/blob/master/translations/zh-Hans/plugin-handbook.md#toc-visiting

参考链接:

https://segmentfault.com/a/1190000013921832

https://www.cnblogs.com/chyingp/p/how-to-write-a-babel-plugin.html

项目所在位置;

https://github.com/18946168254/babel-test.git

 

自制简单的babel插件

原文:https://www.cnblogs.com/fan-zha/p/10980283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!