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


TypeScript babel-types.classBody函数代码示例

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


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

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

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

示例3: JSXElement

} = () => {
  return {
    visitor: {
      JSXElement (path) {
        const arrowFuncExpr = path.findParent(p => p.isArrowFunctionExpression())
        if (arrowFuncExpr && arrowFuncExpr.isArrowFunctionExpression() && arrowFuncExpr.parentPath.isVariableDeclarator()) {
          const valDecl = arrowFuncExpr.parentPath.parentPath
          if (!valDecl.isVariableDeclaration()) {
            throw codeFrameError(valDecl.node, '函数式组件不能同时定义多个值')
          }
          const id = arrowFuncExpr.parentPath.node.id
          if (!t.isIdentifier(id)) {
            throw codeFrameError(id, '函数式组件只能使用普通标识符定义')
          }
          if (!initialIsCapital(id.name)) {
            return
          }
          const hasClassDecl = arrowFuncExpr.findParent(p => p.isClassDeclaration())
          if (hasClassDecl) {
            // @TODO: 加上链接
            return
          }
          const { body } = arrowFuncExpr.node
          if (t.isBlockStatement(body)) {
            valDecl.replaceWith(t.functionDeclaration(id, arrowFuncExpr.node.params, body))
          } else {
            valDecl.replaceWith(t.functionDeclaration(id, arrowFuncExpr.node.params, t.blockStatement([
              t.returnStatement(body)
            ])))
          }
          return
        }

        const functionDecl = path.findParent(p => p.isFunctionDeclaration())
        if (functionDecl && functionDecl.isFunctionDeclaration()) {
          const hasClassDecl = functionDecl.findParent(p => p.isClassDeclaration())
          if (hasClassDecl) {
            // @TODO: 加上链接
            return
          }
          const { id, body, params } = functionDecl.node
          let arg: null | t.LVal = null
          if (params.length > 1) {
            throw codeFrameError(id, '函数式组件的参数最多只能传入一个')
          } else if (params.length === 1) {
            arg = params[0]
          }
          const cloneBody = cloneDeep(body)
          if (!initialIsCapital(id.name)) {
            throw codeFrameError(id, `普通函数式组件命名规则请遵守帕斯卡命名法(Pascal Case), 如果是在函数内声明闭包组件,则需要使用函数表达式的写法。
形如:
const ${id.name} = ${generate(t.arrowFunctionExpression(params, body)).code}
            `)
          }
          if (arg) {
            if (t.isIdentifier(arg)) {
              cloneBody.body.unshift(buildConstVariableDeclaration(arg.name, t.memberExpression(t.thisExpression(), t.identifier('props'))))
            } else if (t.isObjectPattern(arg)) {
              cloneBody.body.unshift(
                t.variableDeclaration('const', [
                  t.variableDeclarator(arg, t.memberExpression(t.thisExpression(), t.identifier('props')))
                ])
              )
            } else {
              throw codeFrameError(arg, '函数式组件只支持传入一个简单标识符或使用对象结构')
            }
          }
          const classDecl = t.classDeclaration(id, t.memberExpression(t.identifier('Taro'), t.identifier('Component')), t.classBody([
            t.classMethod('method', t.identifier('render'), [], cloneBody)
          ]), [])
          functionDecl.replaceWith(classDecl)
        }
      }
    }
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:76,代码来源:functional.ts

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

示例5: 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-types.classBody函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。