当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript babel-traverse.NodePath类代码示例

本文整理汇总了TypeScript中babel-traverse.NodePath的典型用法代码示例。如果您正苦于以下问题:TypeScript NodePath类的具体用法?TypeScript NodePath怎么用?TypeScript NodePath使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了NodePath类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: generateAnonymousState

export function generateAnonymousState (
  scope: Scope,
  expression: NodePath<t.Expression>,
  refIds: Set<t.Identifier>,
  isLogical?: boolean
) {
  let variableName = `anonymousState_${scope.generateUid()}`
  let statementParent = expression.getStatementParent()
  if (!statementParent) {
    throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
  }
  const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
  const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
  const ifExpr = jsx.findParent(p => p.isIfStatement())
  const blockStatement = jsx.findParent(p => p.isBlockStatement() && p.parentPath === ifExpr) as NodePath<t.BlockStatement>
  const expr = setParentCondition(jsx, cloneDeep(expression.node))
  if (!callExpr) {
    refIds.add(t.identifier(variableName))
    statementParent.insertBefore(
      buildConstVariableDeclaration(variableName, expr)
    )
    if (blockStatement && blockStatement.isBlockStatement()) {
      blockStatement.traverse({
        VariableDeclarator: (p) => {
          const { id, init } = p.node
          if (t.isIdentifier(id)) {
            const newId = scope.generateDeclaredUidIdentifier('$' + id.name)
            refIds.forEach((refId) => {
              if (refId.name === variableName && !variableName.startsWith('_$')) {
                refIds.delete(refId)
              }
            })
            variableName = newId.name
            refIds.add(t.identifier(variableName))
            blockStatement.scope.rename(id.name, newId.name)
            p.parentPath.replaceWith(
              template('ID = INIT;')({ ID: newId, INIT: init })
            )
          }
        }
      })
    }
  } else {
    variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
    const func = callExpr.node.arguments[0]
    if (t.isArrowFunctionExpression(func)) {
      if (!t.isBlockStatement(func.body)) {
        func.body = t.blockStatement([
          buildConstVariableDeclaration(variableName, expr),
          t.returnStatement(func.body)
        ])
      } else {
        func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr))
      }
    }
  }
  const id = t.identifier(variableName)
  expression.replaceWith(id)
  return id
}
开发者ID:topud,项目名称:taro,代码行数:60,代码来源:utils.ts

示例2: setParentCondition

export function setParentCondition (jsx: NodePath<t.Node>, expr: t.Expression, array = false) {
  const conditionExpr = jsx.findParent(p => p.isConditionalExpression())
  const logicExpr = jsx.findParent(p => p.isLogicalExpression({ operator: '&&' }))
  if (array) {
    const logicalJSX = jsx.findParent(p => p.isJSXElement() && p.node.openingElement.attributes.some(a => a.name.name === Adapter.if)) as NodePath<t.JSXElement>
    if (logicalJSX) {
      const attr = logicalJSX.node.openingElement.attributes.find(a => a.name.name === Adapter.if)
      if (attr && t.isJSXExpressionContainer(attr.value)) {
        expr = t.conditionalExpression(attr.value.expression, expr, t.arrayExpression())
        return expr
      }
    }
  }
  if (conditionExpr && conditionExpr.isConditionalExpression()) {
    const consequent = conditionExpr.get('consequent')
    if (consequent === jsx || jsx.findParent(p => p === consequent)) {
      expr = t.conditionalExpression(conditionExpr.get('test').node as any, expr, array ? t.arrayExpression([]) : t.nullLiteral())
    }
  }
  if (logicExpr && logicExpr.isLogicalExpression({ operator: '&&' })) {
    const consequent = logicExpr.get('right')
    if (consequent === jsx || jsx.findParent(p => p === consequent)) {
      expr = t.conditionalExpression(logicExpr.get('left').node as any, expr, array ? t.arrayExpression([]) : t.nullLiteral())
    }
  }
  return expr
}
开发者ID:topud,项目名称:taro,代码行数:27,代码来源:utils.ts

示例3: setAncestorCondition

export function setAncestorCondition (jsx: NodePath<t.Node>, expr: t.Expression): t.Expression {
  const ifAttrSet = new Set<string>([
    Adapter.if,
    Adapter.else
  ])
  const logicalJSX = jsx.findParent(p => p.isJSXElement() && p.node.openingElement.attributes.some(a => ifAttrSet.has(a.name.name as string))) as NodePath<t.JSXElement>
  if (logicalJSX) {
    const attr = logicalJSX.node.openingElement.attributes.find(a => ifAttrSet.has(a.name.name as string))
    if (attr) {
      if (attr.name.name === Adapter.else) {
        const prevElement: NodePath<t.JSXElement | null> = (logicalJSX as any).getPrevSibling()
        if (prevElement && prevElement.isJSXElement()) {
          const attr = prevElement.node.openingElement.attributes.find(a => a.name.name === Adapter.if)
          if (attr && t.isJSXExpressionContainer(attr.value)) {
            const condition = reverseBoolean(cloneDeep(attr.value.expression))
            expr = t.logicalExpression('&&', setAncestorCondition(logicalJSX, condition), expr)
          }
        }
      } else if (t.isJSXExpressionContainer(attr.value)) {
        const condition = cloneDeep(attr.value.expression)
        expr = t.logicalExpression('&&', setAncestorCondition(logicalJSX, condition), expr)
      }
    }
  }

  return expr
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:27,代码来源:utils.ts

示例4: findWXIfProps

function findWXIfProps (
  jsx: NodePath<t.Node>
): { reg: RegExpMatchArray; tester: AttrValue } | null {
  let matches: { reg: RegExpMatchArray; tester: AttrValue } | null = null
  jsx &&
    jsx.isJSXElement() &&
    jsx
      .get('openingElement')
      .get('attributes')
      .some(path => {
        const attr = path.node
        if (t.isJSXIdentifier(attr.name)) {
          const name = attr.name.name
          if (name === WX_IF) {
            return true
          }
          const match = name.match(/wx:else|wx:elif/)
          if (match) {
            path.remove()
            matches = {
              reg: match,
              tester: attr.value
            }
            return true
          }
        }
        return false
      })

  return matches
}
开发者ID:topud,项目名称:taro,代码行数:31,代码来源:wxml.ts

示例5: replaceJSXTextWithTextComponent

export function replaceJSXTextWithTextComponent (path: NodePath<t.JSXText | t.JSXExpressionContainer>) {
  const parent = path.findParent(p => p.isJSXElement())
  if (parent && parent.isJSXElement() && t.isJSXIdentifier(parent.node.openingElement.name) && parent.node.openingElement.name.name !== 'Text') {
    path.replaceWith(t.jSXElement(
      t.jSXOpeningElement(t.jSXIdentifier('Text'), []),
      t.jSXClosingElement(t.jSXIdentifier('Text')),
      [path.isJSXText() ? t.jSXText(path.node.value) : path.node]
    ))
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:10,代码来源:utils.ts

示例6: transformLoop

function transformLoop (
  name: string,
  attr: NodePath<t.JSXAttribute>,
  jsx: NodePath<t.JSXElement>,
  value: AttrValue
) {
  if (name !== WX_FOR) {
    return
  }
  if (!value || !t.isJSXExpressionContainer(value)) {
    throw new Error('wx:for 的值必须使用 "{{}}"  包裹')
  }
  attr.remove()
  let item = t.stringLiteral('item')
  let index = t.stringLiteral('index')
  jsx
    .get('openingElement')
    .get('attributes')
    .forEach(p => {
      const node = p.node
      if (node.name.name === WX_FOR_ITEM) {
        if (!node.value || !t.isStringLiteral(node.value)) {
          throw new Error(WX_FOR_ITEM + ' 的值必须是一个字符串')
        }
        item = node.value
        p.remove()
      }
      if (node.name.name === WX_FOR_INDEX) {
        if (!node.value || !t.isStringLiteral(node.value)) {
          throw new Error(WX_FOR_INDEX + ' 的值必须是一个字符串')
        }
        index = node.value
        p.remove()
      }
      if (node.name.name === WX_KEY) {
        p.get('name').replaceWith(t.jSXIdentifier('key'))
      }
    })

  const replacement = t.jSXExpressionContainer(
    t.callExpression(
      t.memberExpression(value.expression, t.identifier('map')),
      [
        t.arrowFunctionExpression(
          [t.identifier(item.value), t.identifier(index.value)],
          t.blockStatement([t.returnStatement(jsx.node)])
        )
      ]
    )
  )

  const block = buildBlockElement()
  block.children = [replacement]
  jsx.replaceWith(block)
}
开发者ID:topud,项目名称:taro,代码行数:55,代码来源:wxml.ts

示例7: generateAnonymousState

export function generateAnonymousState (
  scope: Scope,
  expression: NodePath<t.Expression>,
  refIds: Set<t.Identifier>,
  isLogical?: boolean
) {
  let variableName = `anonymousState_${scope.generateUid()}`
  let statementParent = expression.getStatementParent()
  if (!statementParent) {
    throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
  }
  const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
  const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
  const conditionExpr = jsx.findParent(p => p.isConditionalExpression())
  const logicExpr = jsx.findParent(p => p.isLogicalExpression({ operator: '&&' }))
  let expr = cloneDeep(expression.node)
  if (conditionExpr && conditionExpr.isConditionalExpression()) {
    const consequent = conditionExpr.get('consequent')
    if (consequent === jsx || jsx.findParent(p => p === consequent)) {
      expr = t.conditionalExpression(conditionExpr.get('test').node as any, expr, t.nullLiteral())
    }
  }
  if (logicExpr && logicExpr.isLogicalExpression({ operator: '&&' })) {
    const consequent = logicExpr.get('right')
    if (consequent === jsx || jsx.findParent(p => p === consequent)) {
      expr = t.conditionalExpression(logicExpr.get('left').node as any, expr, t.nullLiteral())
    }
  }
  if (!callExpr) {
    refIds.add(t.identifier(variableName))
    statementParent.insertBefore(
      buildConstVariableDeclaration(variableName, expr)
    )
  } else {
    variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
    const func = callExpr.node.arguments[0]
    if (t.isArrowFunctionExpression(func)) {
      if (!t.isBlockStatement(func.body)) {
        func.body = t.blockStatement([
          buildConstVariableDeclaration(variableName, expr),
          t.returnStatement(func.body)
        ])
      } else {
        statementParent.insertBefore(
          buildConstVariableDeclaration(variableName, expr)
        )
      }
    }
  }
  expression.replaceWith(
    t.identifier(variableName)
  )
}
开发者ID:ApolloRobot,项目名称:taro,代码行数:53,代码来源:utils.ts

示例8: transformIf

function transformIf (
  name: string,
  attr: NodePath<t.JSXAttribute>,
  jsx: NodePath<t.JSXElement>,
  value: AttrValue
) {
  if (name !== WX_IF) {
    return
  }
  const conditions: Condition[] = []
  let siblings: NodePath<t.Node>[] = []
  try {
    siblings = jsx.getAllNextSiblings().filter(s => !(s.isJSXExpressionContainer() && s.get('expression').isJSXEmptyExpression()))
  } catch (error) {
    return
  }
  if (value === null || !t.isJSXExpressionContainer(value)) {
    // tslint:disable-next-line
    console.error('wx:if 的值需要用双括号 `{{}}` 包裹它的值')
    if (value && t.isStringLiteral(value)) {
      value = t.jSXExpressionContainer(buildTemplate(value.value))
    }
  }
  conditions.push({
    condition: WX_IF,
    path: jsx,
    tester: value as t.JSXExpressionContainer
  })
  attr.remove()
  for (let index = 0; index < siblings.length; index++) {
    const sibling = siblings[index]
    const next = cloneDeep(siblings[index + 1])
    const currMatches = findWXIfProps(sibling)
    const nextMatches = findWXIfProps(next)
    if (currMatches === null) {
      break
    }
    conditions.push({
      condition: currMatches.reg.input as string,
      path: sibling as any,
      tester: currMatches.tester as t.JSXExpressionContainer
    })
    if (nextMatches === null) {
      break
    }
  }
  handleConditions(conditions)
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:48,代码来源:wxml.ts

示例9: findDeclarationScope

function findDeclarationScope (path: NodePath<t.Node>, id: t.Identifier) {
  const scopePath = path.findParent(p => !!p.scope.getOwnBindingIdentifier(id.name))
  if (scopePath) {
    return scopePath
  }
  throw codeFrameError(path.node, '该引用从未被定义')
}
开发者ID:topud,项目名称:taro,代码行数:7,代码来源:index.ts

示例10: handleClosureJSXFunc

function handleClosureJSXFunc (jsx: NodePath<t.JSXElement>, mainClass: NodePath<t.ClassDeclaration>) {
  // 在 ./functional.ts 会把 FunctionExpression 转化为 arrowFunctionExpr
  // 所以我们这里只处理一种情况
  const arrowFunc = jsx.findParent(p => p.isArrowFunctionExpression())
  if (arrowFunc && arrowFunc.isArrowFunctionExpression()) {
    const parentPath = arrowFunc.parentPath
    if (parentPath.isVariableDeclarator()) {
      const id = parentPath.node.id
      if (t.isIdentifier(id) && id.name.startsWith('render')) {
        const funcName = `renderClosure${id.name.slice(6, id.name.length)}`
        mainClass.node.body.body.push(
          t.classProperty(
            t.identifier(funcName),
            cloneDeep(arrowFunc.node)
          )
        )
        parentPath.scope.rename(id.name, funcName)
        arrowFunc.replaceWith(t.memberExpression(
          t.thisExpression(),
          t.identifier(funcName)
        ))
      }
    }
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:25,代码来源:index.ts


注:本文中的babel-traverse.NodePath类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。