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


TypeScript NodePath.get方法代码示例

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


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

示例1: 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

示例2: 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

示例3: 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

示例4: cloneDeep

 const jsxAttrVisitor = (path: NodePath<t.JSXAttribute>) => {
   const name = path.node.name as t.JSXIdentifier
   const jsx = path.findParent(p => p.isJSXElement()) as NodePath<
     t.JSXElement
   >
   const valueCopy = cloneDeep(path.get('value').node)
   transformIf(name.name, path, jsx, valueCopy)
   const loopItem = transformLoop(name.name, path, jsx, valueCopy)
   if (loopItem) {
     if (loopItem.index) {
       loopIds.add(loopItem.index)
     }
     if (loopItem.item) {
       loopIds.add(loopItem.item)
     }
   }
 }
开发者ID:YangShaoQun,项目名称:taro,代码行数:17,代码来源:wxml.ts

示例5: parseModule

export function parseModule (jsx: NodePath<t.JSXElement>, dirPath: string, type: 'include' | 'import') {
  const openingElement = jsx.get('openingElement')
  const attrs = openingElement.get('attributes')
  const src = attrs.find(attr => attr.get('name').isJSXIdentifier({ name: 'src' }))
  if (!src) {
    throw new Error(`${type} 标签必须包含 \`src\` 属性`)
  }
  const value = src.get('value')
  if (!value.isStringLiteral()) {
    throw new Error(`${type} 标签的 src 属性值必须是一个字符串`)
  }
  const srcValue = value.node.value
  if (type === 'import') {
    const wxml = getWXMLsource(dirPath, srcValue, type)
    const { imports } = parseWXML(resolve(dirPath, srcValue), wxml, true)
    try {
      jsx.remove()
    } catch (error) {
     //
    }
    return imports
  } else {
    const { wxml } = parseWXML(dirPath, getWXMLsource(dirPath, srcValue, type), true)
    const block = buildBlockElement()
    try {
      if (wxml) {
        block.children = [wxml as any]
        jsx.replaceWith(wxml)
      } else {
        block.children = [t.jSXExpressionContainer(t.jSXEmptyExpression())]
        jsx.replaceWith(block)
      }
    } catch (error) {
      //
    }
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:37,代码来源:template.ts

示例6: 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

示例7:

const isRequireCallExpression = (nodePath: NodePath<CallExpression>) => {
  const callee = nodePath.get("callee");
  return callee.isIdentifier() && callee.equals("name", "require");
};
开发者ID:morlay,项目名称:babel-plugin-webpack-loaders-inline-exports,代码行数:4,代码来源:index.ts

示例8: transformLoop

function transformLoop (
  name: string,
  attr: NodePath<t.JSXAttribute>,
  jsx: NodePath<t.JSXElement>,
  value: AttrValue
) {
  const jsxElement = jsx.get('openingElement')
  if (!jsxElement.node) {
    return
  }
  const attrs = jsxElement.get('attributes').map(a => a.node)
  const wxForItem = attrs.find(a => a.name.name === WX_FOR_ITEM)
  const hasSinglewxForItem = wxForItem && wxForItem.value && t.isJSXExpressionContainer(wxForItem.value)
  if (hasSinglewxForItem || name === WX_FOR || name === 'wx:for-items') {
    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()
        }
      })

    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]
    try {
      jsx.replaceWith(block)
    } catch (error) {
      //
    }

    return {
      item: item.value,
      index: index.value
    }
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:wxml.ts

示例9: 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

示例10: parsePage

function parsePage (
  path: NodePath<t.CallExpression>,
  returned: t.Expression,
  json?: t.ObjectExpression,
  componentType?: string
) {
  const stateKeys: string[] = []
  const propsKeys: string[] = []
  const arg = path.get('arguments')[0]
  if (!arg || !arg.isObjectExpression()) {
    return
  }
  const defaultProps: { name: string, value: any }[] = []
  const props = arg.get('properties')
  const properties = props.filter(p => !p.isSpreadProperty()) as NodePath<
    t.ObjectProperty | t.ObjectMethod
  >[]
  if (properties.length !== props.length) {
    throw new Error(
      '不支持编译在 Page 对象中使用解构(`...` spread property)语法'
    )
  }

  let classBody = properties.map(prop => {
    const key = prop.get('key')
    const value = prop.get('value')
    const 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
    if (name === 'data') {
      if (value.isObjectExpression()) {
        value
          .get('properties')
          .map(p => p.node)
          .forEach(prop => {
            if (t.isObjectProperty(prop)) {
              if (t.isStringLiteral(prop.key)) {
                stateKeys.push(prop.key.value)
              }
              if (t.isIdentifier(prop.key)) {
                stateKeys.push(prop.key.name)
              }
            }
          })
      }
      return t.classProperty(t.identifier('state'), value.node)
    }
    if (name === 'properties') {
      const observeProps: { name: string, observer: any }[] = []
      if (value.isObjectExpression()) {
        value
          .get('properties')
          .map(p => p.node)
          .forEach(prop => {
            if (t.isObjectProperty(prop)) {
              let propKey: string | null = null
              if (t.isStringLiteral(prop.key)) {
                propKey = prop.key.value
              }
              if (t.isIdentifier(prop.key)) {
                propKey = prop.key.name
                // propsKeys.push(prop.key.name)
              }
              if (t.isObjectExpression(prop.value) && propKey) {
                for (const p of prop.value.properties) {
                  if (t.isObjectProperty(p)) {
                    let key: string | null = null
                    if (t.isStringLiteral(p.key)) {
                      key = p.key.value
                    }
                    if (t.isIdentifier(p.key)) {
                      key = p.key.name
                    }
                    if (key === 'value') {
                      defaultProps.push({
                        name: propKey,
                        value: p.value
                      })
                    } else if (key === 'observer') {
                      observeProps.push({
                        name: propKey,
                        observer: p.value
                      })
                    }
                  }
                }
              }
              if (propKey) {
                propsKeys.push(propKey)
//.........这里部分代码省略.........
开发者ID:topud,项目名称:taro,代码行数:101,代码来源:script.ts


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