• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: evalClass

export function evalClass (ast: t.File, props = '', isRequire = false) {
  let mainClass!: t.ClassDeclaration
  const statements = new Set<t.ExpressionStatement>([
    template('Current.inst = this;')() as any
  ])

  traverse(ast, {
    ClassDeclaration (path) {
      mainClass = path.node
    },
    /**
     * 目前 node 的版本支持不了 class-properties
     * 但 babel 又有 bug,某些情况竟然把转换后的 class-properties 编译到 super 之前
     * 不然用 babel.transformFromAst 就完事了
     * 现在只能自己实现这个 feature 的部分功能了,真 tm 麻烦
     * @TODO 有空再给他们提 PR 吧
     */
    ClassProperty (path) {
      const { key, value } = path.node
      statements.add(t.expressionStatement(t.assignmentExpression(
        '=',
        t.memberExpression(
          t.thisExpression(),
          key
        ),
        value
      )))
      path.remove()
    }
  })

  for (const method of mainClass.body.body) {
    // constructor 即便没有被定义也会被加上
    if (t.isClassMethod(method) && method.kind === 'constructor') {
      const index = method.body.body.findIndex(node => t.isSuper(node))
      method.body.body.push(
        t.expressionStatement(t.assignmentExpression(
          '=',
          t.memberExpression(
            t.thisExpression(),
            t.identifier('state')
          ),
          t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('_createData')), [])
        ))
      )
      method.body.body.splice(index, 0, ...statements)
    }
  }

  let code = `function f() {};` +
    generate(t.classDeclaration(t.identifier('Test'), t.identifier('f'), mainClass.body, [])).code +
    ';' + `var classInst =  new Test(${props});classInst`

  code = internalFunction + code

  // tslint:disable-next-line
  return eval(code)
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:58,代码来源:utils.ts


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


示例3: parseAst

export function parseAst (
  type: PARSE_AST_TYPE,
  ast: t.File,
  depComponents: IComponentObj[],
  sourceFilePath: string,
  filePath: string,
  npmSkip: boolean = false
): IParseAstReturn {
  const styleFiles: string[] = []
  const scriptFiles: string[] = []
  const jsonFiles: string[] = []
  const mediaFiles: string[] = []

  const {
    appPath,
    nodeModulesPath,
    npmOutputDir,
    sourceDir,
    outputDir,
    buildAdapter,
    constantsReplaceList,
    isProduction,
    npmConfig,
    alias: pathAlias,
    compileInclude,
    projectConfig
  } = getBuildData()
  const notExistNpmList = getNotExistNpmList()
  const taroMiniAppFramework = `@tarojs/taro-${buildAdapter}`
  let configObj: IConfig = {}
  let componentClassName: string = ''
  let taroJsReduxConnect: string = ''
  let taroImportDefaultName
  let needExportDefault = false
  let exportTaroReduxConnected: string | null = null
  const isQuickApp = buildAdapter === BUILD_TYPES.QUICKAPP
  const cannotRemoves = [taroJsFramework, 'react', 'nervjs']
  let hasComponentDidHide
  let hasComponentDidShow
  let hasComponentWillMount
  let hasEnablePageScroll
  if (isQuickApp) {
    cannotRemoves.push(taroJsComponents)
  }
  const taroSelfComponents = new Set<string>()
  ast = babel.transformFromAst(ast, '', {
    plugins: [
      [require('babel-plugin-danger-remove-unused-import'), { ignore: cannotRemoves }],
      [require('babel-plugin-transform-define').default, constantsReplaceList]
    ]
  }).ast as t.File
  traverse(ast, {
    ClassDeclaration (astPath) {
      const node = astPath.node
      let hasCreateData = false
      if (node.superClass) {
        astPath.traverse({
          ClassMethod (astPath) {
            if (astPath.get('key').isIdentifier({ name: '_createData' })) {
              hasCreateData = true
            }
          }
        })
        if (hasCreateData) {
          needExportDefault = true
          astPath.traverse({
            ClassMethod (astPath) {
              const node = astPath.node
              if (node.kind === 'constructor') {
                astPath.traverse({
                  ExpressionStatement (astPath) {
                    const node = astPath.node
                    if (node.expression &&
                      node.expression.type === 'AssignmentExpression' &&
                      node.expression.operator === '=') {
                      const left = node.expression.left
                      if (left.type === 'MemberExpression' &&
                        left.object.type === 'ThisExpression' &&
                        left.property.type === 'Identifier' &&
                        left.property.name === 'config') {
                        configObj = traverseObjectNode(node.expression.right, buildAdapter)
                      }
                    }
                  }
                })
              }
            }
          })
          if (node.id === null) {
            componentClassName = '_TaroComponentClass'
            astPath.replaceWith(
              t.classDeclaration(
                t.identifier(componentClassName),
                node.superClass as t.Expression,
                node.body as t.ClassBody,
                node.decorators as t.Decorator[] || []
              )
            )
          } else if (node.id.name === 'App') {
            componentClassName = '_App'
//.........这里部分代码省略.........
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:astProcess.ts


示例4: parsePage


//.........这里部分代码省略.........
        return t.classProperty(
          t.identifier(name),
          t.arrowFunctionExpression(params, body.node, isAsync)
        )
      }

      if (hasArguments && (value.isFunctionExpression() || value.isArrowFunctionExpression())) {
        const method = t.classMethod('method', t.identifier(name), params, value.node.body as any)
        method.async = isAsync
        return method
      }

      const classProp = t.classProperty(
        t.identifier(name),
        value.isFunctionExpression() || value.isArrowFunctionExpression()
          ? t.arrowFunctionExpression(value.node.params, value.node.body, isAsync)
          : value.node
      ) as any

      if (staticProps.includes(name)) {
        classProp.static = true
      }

      return classProp
    })

    if (globals.hasCatchTrue) {
      classBody.push(t.classMethod('method', t.identifier('privateStopNoop'), [t.identifier('e')], t.blockStatement([
        t.expressionStatement(
          t.callExpression(
            t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')),
            []
          )
        )
      ])))
    }

    if (defaultProps.length) {
      let classProp = t.classProperty(t.identifier('defaultProps'), t.objectExpression(
        defaultProps.map(p => t.objectProperty(t.identifier(p.name), p.value))
      )) as any
      classProp.static = true
      classBody.unshift(classProp)
    }
  } else if (arg.isIdentifier()) {
    weappConf = arg.node.name
  } else {
    throw codeFrameError(arg.node, `${componentType || '组件'} 的第一个参数必须是一个对象或变量才能转换。`)
  }

  if (json && t.isObjectExpression(json)) {
    classBody.push(t.classProperty(t.identifier('config'), json))
  }

  if (componentType === 'App') {
    let hasWillMount = false
    const globalData = template(`this.$app.globalData = this.globalData`)()
    for (const method of classBody) {
      if (!method) {
        continue
      }
      if (!t.isClassMethod(method)) {
        continue
      }
      if (t.isIdentifier(method.key, { name: Lifecycle.componentWillMount })) {
        hasWillMount = true
        method.body.body.unshift(globalData)
      }
    }
    if (!hasWillMount) {
      classBody.push(
        t.classMethod(
          'method',
          t.identifier(Lifecycle.componentWillMount),
          [],
          t.blockStatement([globalData])
        )
      )
    }
  }

  const wxsNames = new Set(wxses ? wxses.map(w => w.module) : [])

  const renderFunc = buildRender(returned, stateKeys.filter(s => !wxsNames.has(s)), propsKeys)

  const classDecl = t.classDeclaration(
    t.identifier(componentType === 'App' ? 'App' : defaultClassName),
    t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
    t.classBody(
      classBody.concat(renderFunc)
    ),
    []
  )

  if (weappConf) {
    classDecl.decorators = [buildDecorator(componentType || 'Page', weappConf)]
  }

  return classDecl
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:script.ts


示例5: parsePage


//.........这里部分代码省略.........
                }
              }
              if (propKey) {
                propsKeys.push(propKey)
              }
            }
          })
      }
      return t.classProperty(t.identifier('_observeProps'), t.arrayExpression(
        observeProps.map(p => t.objectExpression([
          t.objectProperty(
            t.identifier('name'),
            t.stringLiteral(p.name)
          ),
          t.objectProperty(
            t.identifier('observer'),
            p.observer
          )
        ]))
      ))
    }
    if (PageLifecycle.has(name)) {
      const lifecycle = PageLifecycle.get(name)!
      const node = value.node as
        | t.FunctionExpression
        | t.ArrowFunctionExpression
      const method = t.classMethod(
        'method',
        t.identifier(lifecycle),
        params,
        node ? node.body as t.BlockStatement : (prop.get('body') as any).node
      )
      method.async = isAsync
      return method
    }
    if (prop.isObjectMethod()) {
      const body = prop.get('body')
      return t.classProperty(
        t.identifier(name),
        t.arrowFunctionExpression(params, body.node, isAsync)
      )
    }
    return t.classProperty(
      t.identifier(name),
      value.isFunctionExpression() || value.isArrowFunctionExpression()
        ? t.arrowFunctionExpression(value.node.params, value.node.body, isAsync)
        : value.node
    )
  })

  if (defaultProps.length) {
    let classProp = t.classProperty(t.identifier('defaultProps'), t.objectExpression(
      defaultProps.map(p => t.objectProperty(t.identifier(p.name), p.value))
    )) as any
    classProp.static = true
    classBody.unshift(classProp)
  }

  if (json && t.isObjectExpression(json)) {
    classBody.push(t.classProperty(t.identifier('config'), json))
  }

  if (componentType === 'App') {
    let hasWillMount = false
    const globalData = template(`this.$app.globalData = this.globalData`)()
    for (const method of classBody) {
      if (!method) {
        continue
      }
      if (!t.isClassMethod(method)) {
        continue
      }
      if (t.isIdentifier(method.key, { name: Lifecycle.componentWillMount })) {
        hasWillMount = true
        method.body.body.unshift(globalData)
      }
    }
    if (!hasWillMount) {
      classBody.push(
        t.classMethod(
          'method',
          t.identifier(Lifecycle.componentWillMount),
          [],
          t.blockStatement([globalData])
        )
      )
    }
  }

  const renderFunc = buildRender(returned, stateKeys, propsKeys)

  return t.classDeclaration(
    t.identifier(componentType === 'App' ? 'App' : defaultClassName),
    t.memberExpression(t.identifier('Taro'), t.identifier('Component')),
    t.classBody(
      classBody.concat(renderFunc)
    ),
    []
  )
}
开发者ID:topud,项目名称:taro,代码行数:101,代码来源:script.ts


示例6: enter

const ClassDeclarationOrExpression = {
  enter (astPath) {
    const node = astPath.node
    if (!node.superClass) return
    if (
      node.superClass.type === 'MemberExpression' &&
      node.superClass.object.name === taroImportDefaultName
    ) {
      node.superClass.object.name = taroImportDefaultName
      if (node.id === null) {
        const renameComponentClassName = '_TaroComponentClass'
        componentClassName = renameComponentClassName
        astPath.replaceWith(
          t.classDeclaration(
            t.identifier(renameComponentClassName),
            node.superClass,
            node.body,
            node.decorators || []
          )
        )
      } else {
        componentClassName = node.id.name
      }
    } else if (node.superClass.name === 'Component' || node.superClass.name === 'PureComponent') {
      resetTSClassProperty(node.body.body)
      if (node.id === null) {
        const renameComponentClassName = '_TaroComponentClass'
        componentClassName = renameComponentClassName
        astPath.replaceWith(
          t.classDeclaration(
            t.identifier(renameComponentClassName),
            node.superClass,
开发者ID:YangShaoQun,项目名称:taro,代码行数:32,代码来源:transformJS.ts


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


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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript babel-types.classMethod函数代码示例发布时间:2022-05-25
下一篇:
TypeScript babel-types.classBody函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap