zoukankan      html  css  js  c++  java
  • [AST Tools] Babel template: replace JQuery

    For example we have following code:

    $(el).hide() // el.style.display = 'none'
    $(el).forEach(() => {})
    foo.hide()

    We want

    $(el).hide()

    replace with:

    el.style.display = 'none'

    Plugin:

    export default function (babel) {
      const { types: t, template } = babel;
      
      return {
        name: "ast-transform", // not required
        visitor: {
          CallExpression(path) {
    
              const isJqueryCallExpression = looksLike(path, {
                node: {
                    callee: {
                        name: '$'
                    }
                },
                parent: {
                    type: "MemberExpression",
                    property: {
                        name: 'hide'
                    }
                }
            });
            
            if (!isJqueryCallExpression) {
                return 
            }
            const overallPath = path.parentPath.parentPath;
            const templateString = `EL.style.display = 'none';`
            const assignmentBuilder = template(templateString)
            const assignment = assignmentBuilder({
                EL: t.identifier(path.node.arguments[0].name)
            })
            overallPath.replaceWith(assignment)
          }
        }
      };
    }
    
    
    function looksLike(a, b) {
      return (
        a &&
        b &&
        Object.keys(b).every(bKey => {
          const bVal = b[bKey]
          const aVal = a[bKey]
          if (typeof bVal === 'function') {
            return bVal(aVal)
          }
          return isPrimitive(bVal) ? bVal === aVal : looksLike(aVal, bVal)
        })
      )
    }
    
    function isPrimitive(val) {
      return val == null || /^[sbn]/.test(typeof val)
    }
  • 相关阅读:
    11.网络请求
    关于 Android 开发中的 127.0.0.1 Connection refused ...
    Android的Handler总结(转)
    httpruner3 运行
    allure安装使用
    初来乍到
    修改 SQL SERVER EXPRESS 登录模式
    关于防止用户表单多次提交方案的思考
    C语言static
    Linux ar 命令的使用说明
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12421646.html
Copyright © 2011-2022 走看看