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

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

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

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



在下文中一共展示了thisExpression函数的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: buildRender

export function buildRender (
  returned: t.Expression,
  stateKeys: string[],
  propsKeys: string[],
  templateType?: string | never[]
) {
  const returnStatement: t.Statement[] = [t.returnStatement(returned)]
  if (stateKeys.length) {
    const stateDecl = t.variableDeclaration('const', [
      t.variableDeclarator(
        t.objectPattern(Array.from(new Set(stateKeys)).filter(s => !propsKeys.includes(s)).map(s =>
          t.objectProperty(t.identifier(s), t.identifier(s))
        ) as any),
        t.memberExpression(t.thisExpression(), t.identifier('state'))
      )
    ])
    returnStatement.unshift(stateDecl)
  }

  if (propsKeys.length) {
    let patterns = t.objectPattern(Array.from(new Set(propsKeys)).map(s =>
      t.objectProperty(t.identifier(s), t.identifier(s))
    ) as any)
    if (typeof templateType === 'string') {
      patterns = t.objectPattern([
        t.objectProperty(
          t.identifier('data'),
          templateType === 'wxParseData'
            ? t.objectPattern([t.objectProperty(t.identifier('wxParseData'), t.identifier('wxParseData')) as any]) as any
            : t.identifier(templateType)
        ) as any
      ])
    } else if (Array.isArray(templateType)) {
      patterns = t.objectPattern([
        t.objectProperty(t.identifier('data'), patterns as any) as any
      ])
    }
    const stateDecl = t.variableDeclaration('const', [
      t.variableDeclarator(
        patterns,
        t.memberExpression(t.thisExpression(), t.identifier('props'))
      )
    ])
    returnStatement.unshift(stateDecl)
  }
  return t.classMethod(
    'method',
    t.identifier('render'),
    [],
    t.blockStatement(returnStatement)
  )
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:52,代码来源:utils.ts


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


示例4: parseAttribute

function parseAttribute (attr: Attribute) {
  const { key, value } = attr

  let jsxValue: null | t.JSXExpressionContainer | t.StringLiteral = null

  if (value) {
    const { type, content } = parseContent(value)
    jsxValue =
      type === 'raw'
        ? t.stringLiteral(content)
        : t.jSXExpressionContainer(buildTemplate(content))
  }

  const jsxKey = handleAttrKey(key)
  if (/^on[A-Z]/.test(jsxKey) && jsxValue && t.isStringLiteral(jsxValue)) {
    jsxValue = t.jSXExpressionContainer(
      t.memberExpression(t.thisExpression(), t.identifier(jsxValue.value))
    )
  }
  return t.jSXAttribute(t.jSXIdentifier(jsxKey), jsxValue)
}
开发者ID:topud,项目名称:taro,代码行数:21,代码来源:wxml.ts


示例5: parseAttribute

function parseAttribute (attr: Attribute) {
  let { key, value } = attr
  let jsxValue: null | t.JSXExpressionContainer | t.StringLiteral = null
  if (value) {
    if (key === 'class' && value.startsWith('[') && value.endsWith(']')) {
      value = value.slice(1, value.length - 1).replace(',', '')
      // tslint:disable-next-line
      console.log(codeFrameError(attr, 'Taro/React 不支持 class 传入数组,此写法可能无法得到正确的 class'))
    }
    const { type, content } = parseContent(value)

    if (type === 'raw') {
      jsxValue = t.stringLiteral(content)
    } else {
      let expr: t.Expression
      try {
        expr = buildTemplate(content)
      } catch (error) {
        const pureContent = content.slice(1, content.length - 1)
        if (reserveKeyWords.has(pureContent) && type !== 'raw') {
          const err = `转换模板参数: \`${key}: ${value}\` 报错: \`${pureContent}\` 是 JavaScript 保留字,请不要使用它作为值。`
          if (key === WX_KEY) {
            expr = t.stringLiteral('')
          } else {
            throw new Error(err)
          }
        } else if (content.includes(':')) {
          const [ key, value ] = pureContent.split(':')
          expr = t.objectExpression([t.objectProperty(t.stringLiteral(key), parseExpression(value))])
        } else if (content.includes('...') && content.includes(',')) {
          const objExpr = content.slice(1, content.length - 1).split(',')
          const props: (t.SpreadProperty | t.ObjectProperty)[] = []
          for (const str of objExpr) {
            const s = str.trim()
            if (s.includes('...')) {
              props.push(t.spreadProperty(t.identifier(s.slice(3))))
            } else {
              props.push(t.objectProperty(t.identifier(s), t.identifier(s)))
            }
          }
          expr = t.objectExpression(props)
        } else {
          const err = `转换模板参数: \`${key}: ${value}\` 报错`
          throw new Error(err)
        }
      }
      if (t.isThisExpression(expr)) {
        // tslint:disable-next-line
        console.error('在参数中使用 `this` 可能会造成意想不到的结果,已将此参数修改为 `__placeholder__`,你可以在转换后的代码查找这个关键字修改。')
        expr = t.stringLiteral('__placeholder__')
      }
      jsxValue = t.jSXExpressionContainer(expr)
    }
  }

  const jsxKey = handleAttrKey(key)
  if (/^on[A-Z]/.test(jsxKey) && jsxValue && t.isStringLiteral(jsxValue)) {
    jsxValue = t.jSXExpressionContainer(
      t.memberExpression(t.thisExpression(), t.identifier(jsxValue.value))
    )
  }

  if (key.startsWith('catch') && value && value === 'true') {
    jsxValue = t.jSXExpressionContainer(
      t.memberExpression(t.thisExpression(), t.identifier('privateStopNoop'))
    )
    globals.hasCatchTrue = true
  }
  return t.jSXAttribute(t.jSXIdentifier(jsxKey), jsxValue)
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:70,代码来源:wxml.ts


示例6: cloneDeep

export const createWxmlVistor = (
  loopIds: Set<string>,
  refIds: Set<string>,
  dirPath: string,
  wxses: WXS[] = [],
  imports: Imports[] = []
) => {
  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)
      }
    }
  }
  return {
    JSXAttribute: jsxAttrVisitor,
    JSXIdentifier (path) {
      const nodeName = path.node.name
      if (path.parentPath.isJSXAttribute()) {
        if (nodeName === WX_KEY) {
          path.replaceWith(t.jSXIdentifier('key'))
        }
        if (nodeName.startsWith('wx:') && !wxTemplateCommand.includes(nodeName)) {
          // tslint:disable-next-line
          console.log(`未知 wx 作用域属性: ${nodeName},该属性会被移除掉。`)
          path.parentPath.remove()
        }
      }
    },
    JSXElement: {
      enter (path: NodePath<t.JSXElement>) {
        const openingElement = path.get('openingElement')
        const jsxName = openingElement.get('name')
        const attrs = openingElement.get('attributes')
        if (!jsxName.isJSXIdentifier()) {
          return
        }
        path.traverse({
          Identifier (p) {
            if (!p.isReferencedIdentifier()) {
              return
            }
            const jsxExprContainer = p.findParent(p => p.isJSXExpressionContainer())
            if (!jsxExprContainer || !jsxExprContainer.isJSXExpressionContainer()) {
              return
            }
            if (isValidVarName(p.node.name)) {
              refIds.add(p.node.name)
            }
          },
          JSXAttribute: jsxAttrVisitor
        })
        const slotAttr = attrs.find(a => a.node.name.name === 'slot')
        if (slotAttr) {
          const slotValue = slotAttr.node.value
          if (slotValue && t.isStringLiteral(slotValue)) {
            const slotName = slotValue.value
            const parentComponent = path.findParent(p => p.isJSXElement() && t.isJSXIdentifier(p.node.openingElement.name) && !DEFAULT_Component_SET.has(p.node.openingElement.name.name))
            if (parentComponent && parentComponent.isJSXElement()) {
              slotAttr.remove()
              path.traverse({
                JSXAttribute: jsxAttrVisitor
              })
              const block = buildBlockElement()
              block.children = [cloneDeep(path.node)]
              parentComponent.node.openingElement.attributes.push(
                t.jSXAttribute(
                  t.jSXIdentifier(buildSlotName(slotName)),
                  t.jSXExpressionContainer(block)
                )
              )
              path.remove()
            }
          } else {
            throw codeFrameError(slotValue, 'slot 的值必须是一个字符串')
          }
        }
        const tagName = jsxName.node.name
        if (tagName === 'Slot') {
          const nameAttr = attrs.find(a => a.node.name.name === 'name')
          let slotName = ''
          if (nameAttr) {
            if (nameAttr.node.value && t.isStringLiteral(nameAttr.node.value)) {
              slotName = nameAttr.node.value.value
            } else {
              throw codeFrameError(jsxName.node, 'slot 的值必须是一个字符串')
            }
          }
          const children = t.memberExpression(
            t.memberExpression(t.thisExpression(), t.identifier('props')),
//.........这里部分代码省略.........
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:wxml.ts


示例7: codeFrameError


//.........这里部分代码省略.........
                        })
                      }
                      if (!isValidVarName(propKey)) {
                        throw codeFrameError(prop, `${propKey} 不是一个合法的 JavaScript 变量名`)
                      }
                    }
                    if (t.isObjectMethod(p) && t.isIdentifier(p.key, { name: 'observer' })) {
                      observeProps.push({
                        name: propKey,
                        observer: t.arrowFunctionExpression(p.params, p.body, p.async)
                      })
                    }
                  }
                }
                if (propKey) {
                  propsKeys.push(propKey)
                }
              }
            })
        }
        currentStateKeys.forEach(s => {
          if (propsKeys.includes(s)) {
            throw new Error(`当前 Component 定义了重复的 data 和 properites: ${s}`)
          }
        })
        stateKeys.push(...currentStateKeys)
        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)!
        if (name === 'onLoad' && t.isIdentifier(params[0])) {
          params = [t.assignmentPattern(params[0] as t.Identifier, t.logicalExpression('||', t.memberExpression(
            t.memberExpression(
              t.thisExpression(),
              t.identifier('$router')
            ),
            t.identifier('params')
          ), t.objectExpression([])))]
        }
        if (prop.isObjectMethod()) {
          const body = prop.get('body')
          return t.classMethod('method', t.identifier(lifecycle), params, body.node)
        }
        const node = value.node
        const method = t.isFunctionExpression(node) || t.isArrowFunctionExpression(node)
          ? t.classProperty(t.identifier(lifecycle), t.arrowFunctionExpression(params, node.body, isAsync))
          : t.classProperty(t.identifier(lifecycle), node)
        return method
      }
      let hasArguments = false
      prop.traverse({
        Identifier (path) {
          if (path.node.name === 'arguments') {
            hasArguments = true
            path.stop()
          }
        }
      })

      if (prop.isObjectMethod()) {
        const body = prop.get('body')
        if (hasArguments) {
          return t.classMethod('method', t.identifier(name), params, body.node)
        }
        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
    })
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:script.ts


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
TypeScript babel-types.unaryExpression函数代码示例发布时间:2022-05-25
下一篇:
TypeScript babel-types.stringLiteral函数代码示例发布时间: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