當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript NodePath.traverse方法代碼示例

本文整理匯總了TypeScript中babel-traverse.NodePath.traverse方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript NodePath.traverse方法的具體用法?TypeScript NodePath.traverse怎麽用?TypeScript NodePath.traverse使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在babel-traverse.NodePath的用法示例。


在下文中一共展示了NodePath.traverse方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: isContainFunction

export function isContainFunction (p: NodePath<t.Node>) {
  let bool = false
  p.traverse({
    CallExpression () {
      bool = true
    }
  })
  return bool
}
開發者ID:topud,項目名稱:taro,代碼行數:9,代碼來源:utils.ts

示例2: isContainJSXElement

export function isContainJSXElement (path: NodePath<t.Node>) {
  let matched = false
  path.traverse({
    JSXElement (p) {
      matched = true
      p.stop()
    }
  })
  return matched
}
開發者ID:topud,項目名稱:taro,代碼行數:10,代碼來源:utils.ts

示例3: isContainStopPropagation

export function isContainStopPropagation (path: NodePath<t.Node> | null | undefined) {
  let matched = false
  if (path) {
    path.traverse({
      Identifier (p) {
        if (
          p.node.name === 'stopPropagation' &&
          p.parentPath.parentPath.isCallExpression()
        ) {
          matched = true
        }
      }
    })
  }
  return matched
}
開發者ID:YangShaoQun,項目名稱:taro,代碼行數:16,代碼來源:utils.ts

示例4: hasComplexExpression

export function hasComplexExpression (path: NodePath<t.Node>) {
  let matched = false
  if (isContainJSXElement(path)) {
    return false
  }
  if (path.isTemplateLiteral() || path.isCallExpression()) {
    return true
  }
  path.traverse({
    CallExpression: (p) => {
      matched = true
      p.stop()
    },
    TemplateLiteral (p) {
      matched = true
      p.stop()
    },
    TaggedTemplateExpression (p) {
      matched = true
      p.stop()
    },
    MemberExpression (path) {
      const jsxElement = path.findParent(p => p.isJSXExpressionContainer())
      const object = path.get('object')
      const property = path.get('property')
      const parentPath = path.parentPath
      if (
        jsxElement &&
        object.isThisExpression() &&
        property.isIdentifier({ name: 'state' }) &&
        parentPath.isMemberExpression() &&
        parentPath.parentPath.isMemberExpression()
      ) {
        const sourceCode = parentPath.parentPath.getSource()
        if (sourceCode.includes('[') && sourceCode.includes(']')) {
          matched = true
          path.stop()
        }
      }
    }
  })
  return matched
}
開發者ID:ApolloRobot,項目名稱:taro,代碼行數:43,代碼來源:utils.ts

示例5: parseTemplate

export function parseTemplate (path: NodePath<t.JSXElement>, dirPath: string) {
  const openingElement = path.get('openingElement')
  const attrs = openingElement.get('attributes')
  const is = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'is' }))
  const data = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'data' }))
  // const spread = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'spread' }))
  const name = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'name' }))
  const refIds = new Set<string>()
  if (name) {
    const value = name.node.value
    if (value === null || !t.isStringLiteral(value)) {
      throw new Error('template 的 `name` 屬性隻能是字符串')
    }
    const className = pascalName(value.value) + pascalName(basename(dirPath))
    path.traverse({
      Identifier (p) {
        if (!p.isReferencedIdentifier()) {
          return
        }
        const jsxExprContainer = p.findParent(p => p.isJSXExpressionContainer())
        if (!jsxExprContainer || !jsxExprContainer.isJSXExpressionContainer()) {
          return
        }
        refIds.add(p.node.name)
      }
    })

    const block = buildBlockElement()
    block.children = path.node.children
    let render: t.ClassMethod
    if (refIds.size === 0) {
      // 無狀態組件
      render = buildRender(block, [], [])
    } else if (refIds.size === 1) {
      // 隻有一個數據源
      render = buildRender(block, [], Array.from(refIds), Array.from(refIds)[0])
    } else {
      // 使用 ...spread
      render = buildRender(block, [], Array.from(refIds), [])
    }

    const classDecl = t.classDeclaration(
      t.identifier(className),
      t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
      t.classBody([render!]),
      []
    )
    path.remove()
    return {
      name: className,
      ast: classDecl
    }
  } else if (is) {
    const value = is.node.value
    if (!value) {
      throw new Error('template 的 `is` 屬性不能為空')
    }
    if (t.isStringLiteral(value)) {
      const className = pascalName(value.value)
      let attributes: t.JSXAttribute[] = []
      if (data) {
        attributes.push(data.node)
      }
      path.replaceWith(t.jSXElement(
        t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
        t.jSXClosingElement(t.jSXIdentifier(className)),
        [],
        true
      ))
    } else if (t.isJSXExpressionContainer(value)) {
      if (t.isStringLiteral(value.expression)) {
        const className = pascalName(value.expression.value)
        let attributes: t.JSXAttribute[] = []
        if (data) {
          attributes.push(data.node)
        }
        path.replaceWith(t.jSXElement(
          t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
          t.jSXClosingElement(t.jSXIdentifier(className)),
          [],
          true
        ))
      } else if (t.isConditional(value.expression)) {
        const { test, consequent, alternate } = value.expression
        if (!t.isStringLiteral(consequent) || !t.isStringLiteral(alternate)) {
          throw new Error('當 template is 標簽是三元表達式時,他的兩個值都必須為字符串')
        }
        let attributes: t.JSXAttribute[] = []
        if (data) {
          attributes.push(data.node)
        }
        const block = buildBlockElement()
        block.children = [t.jSXExpressionContainer(t.conditionalExpression(
          test,
          t.jSXElement(
            t.jSXOpeningElement(t.jSXIdentifier('Template'), attributes.concat(
              [t.jSXAttribute(t.jSXIdentifier('is'), consequent)]
            )),
            t.jSXClosingElement(t.jSXIdentifier('Template')),
            [],
//.........這裏部分代碼省略.........
開發者ID:topud,項目名稱:taro,代碼行數:101,代碼來源:template.ts

示例6: parseLoopBody

export function parseLoopBody (
  body: NodePath<t.BlockStatement>,
  jsxDeclarations: Set<NodePath<t.Node>>,
  // @TODO
  // 把 templates 換成 Map 可以支持 shalow variables declared
  // 現在先用 ESLint 的 no-shalow 頂著
  templates: Map<string, t.JSXElement>,
  loopScopes: Set<string>,
  finalReturnElement: t.JSXElement,
  returnedPaths: NodePath<t.Node>[]
) {
  const bodyScope = body.scope
  body.traverse({
    JSXElement (jsxElementPath) {
      const parentNode = jsxElementPath.parent
      const parentPath = jsxElementPath.parentPath
      const isFinalReturn = jsxElementPath.getFunctionParent().isClassMethod()
      const isJSXChildren = t.isJSXElement(parentNode)
      if (!isJSXChildren) {
        let statementParent = jsxElementPath.getStatementParent()
        if (
          !(
            statementParent.isVariableDeclaration() ||
            statementParent.isExpressionStatement()
          )
        ) {
          statementParent = statementParent.findParent(
            s => s.isVariableDeclaration() || s.isExpressionStatement()
          ) as NodePath<t.Statement>
        }
        jsxDeclarations.add(statementParent)
        if (t.isVariableDeclarator(parentNode)) {
          if (statementParent) {
            const name = findIdentifierFromStatement(statementParent.node as t.VariableDeclaration)
            // setTemplate(name, path, templates)
            name && templates.set(name, jsxElementPath.node)
          }
        } else if (t.isLogicalExpression(parentNode)) {
          const { left, operator } = parentNode
          if (operator === '&&') {
            if (t.isExpression(left)) {
              newJSXIfAttr(jsxElementPath.node, left)
              parentPath.replaceWith(jsxElementPath.node)
              if (statementParent) {
                const name = findIdentifierFromStatement(statementParent.node as t.VariableDeclaration)
                setTemplate(name, jsxElementPath, templates)
                // name && templates.set(name, path.node)
              }
            }
          }
        } else if (t.isConditionalExpression(parentNode)) {
          const { test, consequent, alternate } = parentNode
          const block = buildBlockElement()
          if (t.isJSXElement(consequent) && t.isLiteral(alternate)) {
            const { value, confident } = parentPath.get('alternate').evaluate()
            if (confident && !value) {
              newJSXIfAttr(block, test)
              block.children = [ jsxElementPath.node ]
              // newJSXIfAttr(jsxElementPath.node, test)
              parentPath.replaceWith(block)
              if (statementParent) {
                const name = findIdentifierFromStatement(
                  statementParent.node as t.VariableDeclaration
                )
                setTemplate(name, jsxElementPath, templates)
                // name && templates.set(name, path.node)
              }
            }
          } else if (t.isLiteral(consequent) && t.isJSXElement(consequent)) {
            if (t.isNullLiteral(consequent)) {
              newJSXIfAttr(block, reverseBoolean(test))
              // newJSXIfAttr(jsxElementPath.node, reverseBoolean(test))
              parentPath.replaceWith(block)
              if (statementParent) {
                const name = findIdentifierFromStatement(
                  statementParent.node as t.VariableDeclaration
                )
                setTemplate(name, jsxElementPath, templates)
                // name && templates.set(name, path.node)
              }
            }
          } else if (t.isJSXElement(consequent) && t.isJSXElement(alternate)) {
            const block2 = buildBlockElement()
            block.children = [consequent]
            newJSXIfAttr(block, test)
            setJSXAttr(block2, Adapter.else)
            block2.children = [alternate]
            const parentBlock = buildBlockElement()
            parentBlock.children = [block, block2]
            parentPath.replaceWith(parentBlock)
            if (statementParent) {
              const name = findIdentifierFromStatement(
                statementParent.node as t.VariableDeclaration
              )
              setTemplate(name, jsxElementPath, templates)
            }
          } else {
            // console.log('todo')
          }
        } else if (t.isReturnStatement(parentNode)) {
//.........這裏部分代碼省略.........
開發者ID:AlloyTeam,項目名稱:Nuclear,代碼行數:101,代碼來源:loop-component.ts

示例7: parsePage

function parsePage (
  pagePath: NodePath<t.CallExpression>,
  returned: t.Expression,
  json?: t.ObjectExpression,
  componentType?: string,
  refId?: Set<string>,
  wxses?: WXS[]
) {
  const stateKeys: string[] = []
  let weappConf: string | null = null
  let methods: NodePath<
    t.ObjectProperty | t.ObjectMethod
  >[] = []
  pagePath.traverse({
    CallExpression (path) {
      const callee = path.get('callee')
      if (callee.isIdentifier()) {
        const name = callee.node.name
        if (name === 'getApp' || name === 'getCurrentPages') {
          callee.replaceWith(
            t.memberExpression(t.identifier('Taro'), callee.node)
          )
        }
      }
      if (callee.isMemberExpression()) {
        const object = callee.get('object')
        const property = callee.get('property')
        if (object.isIdentifier()) {
          const objectName = object.node.name
          if (objectName === 'wx') {
            object.replaceWith(t.identifier('Taro'))
          }
        }

        let isThis = property.isThisExpression()

        if (property.isIdentifier() && object.isIdentifier()) {
          const propertyName = property.node.name
          const objectName = object.node.name
          if (PageLifecycle.has(propertyName) && isAliasThis(property, objectName)) {
            isThis = true
          }

          if (isThis && PageLifecycle.has(propertyName)) {
            property.replaceWith(t.identifier(PageLifecycle.get(propertyName)))
          }
        }
      }
    },
    ObjectProperty (path) {
      const { key, value } = path.node
      if (!t.isIdentifier(key, { name: 'methods' }) || path.parentPath !== pagePath.get('arguments')[0] || !t.isObjectExpression(value)) {
        return
      }
      methods = path.get('value.properties') as NodePath<
        t.ObjectProperty | t.ObjectMethod
      >[]
      path.remove()
    }
  })
  if (refId) {
    refId.forEach(id => {
      if (!stateKeys.includes(id)) {
        stateKeys.push(id)
      }
    })
  }
  const propsKeys: string[] = []
  const arg = pagePath.get('arguments')[0]

  let classBody: any = []
  if (arg.isObjectExpression()) {
    const defaultProps: { name: string, value: any }[] = []
    const props = arg.get('properties')
    const properties = props.filter(p => !p.isSpreadProperty()).concat(methods) as NodePath<
      t.ObjectProperty | t.ObjectMethod
    >[]

    classBody = properties.map(prop => {
      const key = prop.get('key')
      const value = prop.get('value')
      let params = prop.isObjectMethod()
        ? prop.node.params
        : value.isFunctionExpression() || value.isArrowFunctionExpression()
          ? value.node.params
          : []
      const isAsync = prop.isObjectMethod()
        ? prop.node.async
        : value.isFunctionExpression() || value.isArrowFunctionExpression()
          ? value.node.async
          : false
      if (!key.isIdentifier()) {
        throw codeFrameError(key.node, 'Page 對象的鍵值隻能是字符串')
      }
      const name = key.node.name
      const currentStateKeys: string[] = []
      if (name === 'data') {
        if (value.isObjectExpression()) {
          value
            .get('properties')
//.........這裏部分代碼省略.........
開發者ID:YangShaoQun,項目名稱:taro,代碼行數:101,代碼來源:script.ts

示例8: parseTemplate

export function parseTemplate (path: NodePath<t.JSXElement>, dirPath: string) {
  if (!path.container) {
    return
  }
  const openingElement = path.get('openingElement')
  const attrs = openingElement.get('attributes')
  const is = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'is' }))
  const data = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'data' }))
  // const spread = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'spread' }))
  const name = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'name' }))
  const refIds = new Set<string>()
  const loopIds = new Set<string>()
  let imports: any[] = []
  if (name) {
    const value = name.node.value
    if (value === null || !t.isStringLiteral(value)) {
      throw new Error('template 的 `name` 屬性隻能是字符串')
    }
    const className = buildTemplateName(value.value)

    path.traverse(createWxmlVistor(loopIds, refIds, dirPath, [], imports))
    const firstId = Array.from(refIds)[0]
    refIds.forEach(id => {
      if (loopIds.has(id) && id !== firstId) {
        refIds.delete(id)
      }
    })

    const block = buildBlockElement()
    block.children = path.node.children
    let render: t.ClassMethod
    if (refIds.size === 0) {
      // 無狀態組件
      render = buildRender(block, [], [])
    } else if (refIds.size === 1) {
      // 隻有一個數據源
      render = buildRender(block, [], Array.from(refIds), firstId)
    } else {
      // 使用 ...spread
      render = buildRender(block, [], Array.from(refIds), [])
    }
    const classProp = t.classProperty(t.identifier('options'), t.objectExpression([
      t.objectProperty(
        t.identifier('addGlobalClass'),
        t.booleanLiteral(true)
      )
    ])) as any
    classProp.static = true
    const classDecl = t.classDeclaration(
      t.identifier(className),
      t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
      t.classBody([render, classProp]),
      []
    )
    path.remove()
    return {
      name: className,
      ast: classDecl
    }
  } else if (is) {
    const value = is.node.value
    if (!value) {
      throw new Error('template 的 `is` 屬性不能為空')
    }
    if (t.isStringLiteral(value)) {
      const className = buildTemplateName(value.value)
      let attributes: t.JSXAttribute[] = []
      if (data) {
        attributes.push(data.node)
      }
      path.replaceWith(t.jSXElement(
        t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
        t.jSXClosingElement(t.jSXIdentifier(className)),
        [],
        true
      ))
    } else if (t.isJSXExpressionContainer(value)) {
      if (t.isStringLiteral(value.expression)) {
        const className = buildTemplateName(value.expression.value)
        let attributes: t.JSXAttribute[] = []
        if (data) {
          attributes.push(data.node)
        }
        path.replaceWith(t.jSXElement(
          t.jSXOpeningElement(t.jSXIdentifier(className), attributes),
          t.jSXClosingElement(t.jSXIdentifier(className)),
          [],
          true
        ))
      } else if (t.isConditional(value.expression)) {
        const { test, consequent, alternate } = value.expression
        if (!t.isStringLiteral(consequent) || !t.isStringLiteral(alternate)) {
          throw new Error('當 template is 標簽是三元表達式時,他的兩個值都必須為字符串')
        }
        let attributes: t.JSXAttribute[] = []
        if (data) {
          attributes.push(data.node)
        }
        const block = buildBlockElement()
        block.children = [t.jSXExpressionContainer(t.conditionalExpression(
//.........這裏部分代碼省略.........
開發者ID:YangShaoQun,項目名稱:taro,代碼行數:101,代碼來源:template.ts


注:本文中的babel-traverse.NodePath.traverse方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。