首页 > Web开发 > 详细

[AST Tools] Babel template: replace JQuery

时间:2020-03-05 18:06:26      阅读:82      评论:0      收藏:0      [点我收藏+]

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)
}

 

[AST Tools] Babel template: replace JQuery

原文:https://www.cnblogs.com/Answer1215/p/12421646.html

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