zoukankan      html  css  js  c++  java
  • 自制简单的babel插件

    示例

    一个用于生产时 去掉代码中 所有的打印代码,如 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:workspaceabel	est>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

  • 相关阅读:
    1360 奇怪的电梯(lift)
    1249 Lake Counting
    1330 【例8.3】最少步数
    1329 【例8.2】细胞
    1215 迷宫
    垃圾树
    vector
    1970:【15NOIP普及组】扫雷游戏
    1251:仙岛求药
    Python3+PCAN-USB基于PCAN-Basic二次开发实现上位机功能
  • 原文地址:https://www.cnblogs.com/fan-zha/p/10980283.html
Copyright © 2011-2022 走看看