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


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

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


在下文中一共展示了memberExpression函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: it

it('should move static apis under "Taro"', function () {
  const code = `
    import { noop } from '@tarojs/taro-h5';
    noop;
    noop();
  `

  const result = babel.transform(code, { plugins: [pluginOptions] })
  expect(result.code).toMatchSnapshot();

  const ast = result.ast as t.File
  const body = ast.program.body as [t.ImportDeclaration, t.ExpressionStatement]
  expect(t.isImportDeclaration(body[0])).toBeTruthy()
  expect(t.isExpressionStatement(body[1])).toBeTruthy()
  const defaultImport = body[0].specifiers.find(v => t.isImportDefaultSpecifier(v))
  expect(defaultImport).toBeTruthy()

  const taroName = defaultImport!.local.name
  let memberExpression = body[1].expression
  if (t.isCallExpression(body[1])) {
    memberExpression = (body[1].expression as t.CallExpression).callee
  }
  expect(memberExpression).toMatchObject(t.memberExpression(
    t.identifier(taroName),
    t.identifier('noop')
  ))
})
开发者ID:YangShaoQun,项目名称:taro,代码行数:27,代码来源:index-test.ts

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

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

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

示例7: parseScript

export function parseScript (
  script?: string,
  returned?: t.Expression,
  json?: t.ObjectExpression,
  wxses: WXS[] = [],
  refId?: Set<string>
) {
  script = script || 'Page({})'
  if (t.isJSXText(returned as any)) {
    const block = buildBlockElement()
    block.children = [returned as any]
    returned = block
  }
  let ast = parseCode(script)
  let classDecl!: t.ClassDeclaration
  let foundWXInstance = false
  const vistor: Visitor = {
    BlockStatement (path) {
      path.scope.rename('wx', 'Taro')
    },
    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')
        if (object.isIdentifier({ name: 'wx' })) {
          object.replaceWith(t.identifier('Taro'))
        }
      }
      if (
        callee.isIdentifier({ name: 'Page' }) ||
        callee.isIdentifier({ name: 'Component' }) ||
        callee.isIdentifier({ name: 'App' })
      ) {
        foundWXInstance = true
        const componentType = callee.node.name
        classDecl = parsePage(
          path,
          returned || t.nullLiteral(),
          json,
          componentType,
          refId,
          wxses
        )
        if (componentType !== 'App' && classDecl.decorators!.length === 0) {
          classDecl.decorators = [buildDecorator(componentType)]
        }
        ast.program.body.push(
          classDecl,
          t.exportDefaultDeclaration(t.identifier(componentType !== 'App' ? defaultClassName : 'App'))
        )
        // path.insertAfter(t.exportDefaultDeclaration(t.identifier(defaultClassName)))
        path.remove()
      }
    }
  }

  traverse(ast, vistor)

  if (!foundWXInstance) {
    ast = parseCode(script + ';Component({})')
    traverse(ast, vistor)
  }

  const taroComponentsImport = buildImportStatement('@tarojs/components', [
    ...usedComponents
  ])
  const taroImport = buildImportStatement('@tarojs/taro', [], 'Taro')
  const withWeappImport = buildImportStatement(
    '@tarojs/with-weapp',
    [],
    'withWeapp'
  )
  ast.program.body.unshift(
    taroComponentsImport,
    taroImport,
    withWeappImport,
    ...wxses.filter(wxs => !wxs.src.startsWith('./wxs__')).map(wxs => buildImportStatement(wxs.src, [], wxs.module))
  )

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

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

示例9: parseAst


//.........这里部分代码省略.........
                    ClassMethod (astPath) {
                      if (astPath.get('key').isIdentifier({ name: 'render' })) {
                        astPath.traverse({
                          JSXElement () {
                            isTaroComponent = true
                          }
                        })
                      }
                    }
                  })
                  if (isTaroComponent) {
                    componentClassName = declaration.id.name
                  }
                }
              }
            },
            ImportDeclaration (astPath) {
              const node = astPath.node
              const source = node.source
              const value = source.value
              analyzeImportUrl(sourceFilePath, scriptFiles, source, value)
            },
            CallExpression (astPath) {
              const node = astPath.node
              const calleePath = astPath.get('callee')
              const callee = calleePath.node
              if (callee.type === 'Identifier') {
                if (callee.name === 'require') {
                  const args = node.arguments as Array<t.StringLiteral>
                  const value = args[0].value
                  analyzeImportUrl(sourceFilePath, scriptFiles, args[0], value)
                } else if (WX_GLOBAL_FN.has(callee.name)) {
                  calleePath.replaceWith(
                    t.memberExpression(t.identifier('Taro'), callee as t.Identifier)
                  )
                  needInsertImportTaro = true
                }
              } else if (callee.type === 'MemberExpression') {
                const object = callee.object as t.Identifier
                if (object.name === 'wx') {
                  (calleePath.get('object') as NodePath).replaceWith(t.identifier('Taro'))
                  needInsertImportTaro = true
                }
              }
            }
          })
        },
        exit (astPath) {
          const bodyNode = astPath.get('body') as NodePath<t.Node>[]
          const lastImport = bodyNode.filter(p => p.isImportDeclaration()).pop()
          const hasTaroImport = bodyNode.some(p => p.isImportDeclaration() && p.node.source.value === '@tarojs/taro')
          if (needInsertImportTaro && !hasTaroImport) {
            (astPath.node as t.Program).body.unshift(
              t.importDeclaration(
                [t.importDefaultSpecifier(t.identifier('Taro'))],
                t.stringLiteral('@tarojs/taro')
              )
            )
          }
          astPath.traverse({
            StringLiteral (astPath) {
              const value = astPath.node.value
              const extname = path.extname(value)
              if (extname && REG_IMAGE.test(extname) && !REG_URL.test(value)) {
                let imageRelativePath: string
                let sourceImagePath: string
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:index.ts


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