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

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

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

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



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

示例1:

 observeProps.map(p => t.objectExpression([
   t.objectProperty(
     t.identifier('name'),
     t.stringLiteral(p.name)
   ),
   t.objectProperty(
     t.identifier('observer'),
     p.observer
   )
 ]))
开发者ID:YangShaoQun,项目名称:taro,代码行数:10,代码来源:script.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: findParentLoops

export function findParentLoops (
  callee: NodePath<t.CallExpression>,
  names: Map<NodePath<t.CallExpression>, string>,
  loops: t.ArrayExpression
) {
  let indexId: t.Identifier | null = null
  let name: string | undefined
  const [ func ] = callee.node.arguments
  if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) {
    const params = func.params as t.Identifier[]
    indexId = params[1]
    name = names.get(callee)
  }

  if (indexId === null || !t.isIdentifier(indexId)) {
    indexId = t.identifier(callee.scope.generateUid('anonIdx'));
    (func as any).params = [(func as any).params[0], indexId]
  }

  if (!name) {
    throw codeFrameError(callee.node, '找不到循环对应的名称')
  }

  loops.elements.unshift(t.objectExpression([
    t.objectProperty(t.identifier('indexId'), indexId),
    t.objectProperty(t.identifier('name'), t.stringLiteral(name))
  ]))

  const parentCallExpr = callee.findParent(p => p.isCallExpression())
  if (parentCallExpr && parentCallExpr.isCallExpression()) {
    const callee = parentCallExpr.node.callee
    if (
      t.isMemberExpression(callee) &&
      t.isIdentifier(callee.property) &&
      callee.property.name === 'map'
    ) {
      findParentLoops(parentCallExpr, names, loops)
    }
  }
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:40,代码来源:utils.ts


示例4:

 const objArr = Object.keys(obj).map(key => {
   const value = obj[key]
   if (typeof value === 'string') {
     return t.objectProperty(t.stringLiteral(key), t.stringLiteral(value))
   }
   if (typeof value === 'number') {
     return t.objectProperty(t.stringLiteral(key), t.numericLiteral(value))
   }
   if (typeof value === 'boolean') {
     return t.objectProperty(t.stringLiteral(key), t.booleanLiteral(value))
   }
   if (Array.isArray(value)) {
     return t.objectProperty(t.stringLiteral(key), t.arrayExpression(convertArrayToAstExpression(value as [])))
   }
   if (typeof value === 'object') {
     return t.objectProperty(t.stringLiteral(key), t.objectExpression(convertObjectToAstExpression(value)))
   }
   return t.objectProperty(t.stringLiteral(key), t.nullLiteral())
 })
开发者ID:YangShaoQun,项目名称:taro,代码行数:19,代码来源:astConvert.ts


示例5: _rewriteDynamicImport

 /**
  * Extends dynamic import statements to extract the explicitly namespace
  * export for the imported module.
  *
  * Before:
  *     import('./module-a.js')
  *         .then((moduleA) => moduleA.doSomething());
  *
  * After:
  *     import('./bundle_1.js')
  *         .then(({$moduleA}) => $moduleA)
  *         .then((moduleA) => moduleA.doSomething());
  */
 private _rewriteDynamicImport(
     baseUrl: ResolvedUrl,
     root: babel.Node,
     importNodePath: NodePath) {
   if (!importNodePath) {
     return;
   }
   const importCallExpression = importNodePath.parent;
   if (!importCallExpression ||
       !babel.isCallExpression(importCallExpression)) {
     return;
   }
   const importCallArgument = importCallExpression.arguments[0];
   if (!babel.isStringLiteral(importCallArgument)) {
     return;
   }
   const sourceUrl = importCallArgument.value;
   const resolvedSourceUrl = this.bundler.analyzer.urlResolver.resolve(
       baseUrl, sourceUrl as FileRelativeUrl);
   if (!resolvedSourceUrl) {
     return;
   }
   const sourceBundle = this.manifest.getBundleForFile(resolvedSourceUrl);
   // TODO(usergenic): To support *skipping* the rewrite, we need a way to
   // identify whether a bundle contains a single top-level module or is a
   // merged bundle with multiple top-level modules.
   let exportName;
   if (sourceBundle) {
     exportName =
         getOrSetBundleModuleExportName(sourceBundle, resolvedSourceUrl, '*');
   }
   // If there's no source bundle or the namespace export name of the bundle
   // is just '*', then we don't need to append a .then() to transform the
   // return value of the import().  Lets just rewrite the URL to be a relative
   // path and exit.
   if (!sourceBundle || exportName === '*') {
     const relativeSourceUrl =
         ensureLeadingDot(this.bundler.analyzer.urlResolver.relative(
             baseUrl, resolvedSourceUrl));
     importCallArgument.value = relativeSourceUrl;
     return;
   }
   // Rewrite the URL to be a relative path to the bundle.
   const relativeSourceUrl = ensureLeadingDot(
       this.bundler.analyzer.urlResolver.relative(baseUrl, sourceBundle.url));
   importCallArgument.value = relativeSourceUrl;
   const importCallExpressionParent = importNodePath.parentPath.parent!;
   if (!importCallExpressionParent) {
     return;
   }
   const thenifiedCallExpression = babel.callExpression(
       babel.memberExpression(
           clone(importCallExpression), babel.identifier('then')),
       [babel.arrowFunctionExpression(
           [
             babel.objectPattern(
                 [babel.objectProperty(
                      babel.identifier(exportName),
                      babel.identifier(exportName),
                      undefined,
                      true) as any]),
           ],
           babel.identifier(exportName))]);
   rewriteObject(importCallExpression, thenifiedCallExpression);
 }
开发者ID:Polymer,项目名称:vulcanize,代码行数:78,代码来源:es6-rewriter.ts


示例6: parseAst


//.........这里部分代码省略.........
              }
              if (!npmSkip) {
                args[0].value = getExactedNpmFilePath({
                  npmName: value,
                  sourceFilePath,
                  filePath,
                  isProduction,
                  npmConfig,
                  buildAdapter,
                  root: appPath,
                  npmOutputDir,
                  compileInclude,
                  env: projectConfig.env || {},
                  uglify: projectConfig!.plugins!.uglify || {},
                  babelConfig: projectConfig!.plugins!.babel || {}
                })
              } else {
                args[0].value = value
              }
            }
          }
        } else if (CSS_EXT.indexOf(path.extname(value)) !== -1 && t.isVariableDeclarator(astPath.parentPath)) { // 对 使用 const style = require('./style.css') 语法引入的做转化处理
          printLog(processTypeEnum.GENERATE, '替换代码', `为文件 ${sourceFilePath} 生成 css modules`)
          const styleFilePath = path.join(path.dirname(sourceFilePath), value)
          const styleCode = fs.readFileSync(styleFilePath).toString()
          const result = processStyleUseCssModule({
            css: styleCode,
            filePath: styleFilePath
          })
          const tokens = result.root.exports || {}
          const objectPropperties: t.ObjectProperty[] = []
          for (const key in tokens) {
            if (tokens.hasOwnProperty(key)) {
              objectPropperties.push(t.objectProperty(t.identifier(key), t.stringLiteral(tokens[key])))
            }
          }
          astPath.replaceWith(t.objectExpression(objectPropperties))
          if (styleFiles.indexOf(styleFilePath) < 0) { // add this css file to queue
            styleFiles.push(styleFilePath)
          }
        } else if (path.isAbsolute(value)) {
          printLog(processTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`)
        }
      }
    },

    ExportDefaultDeclaration (astPath) {
      const node = astPath.node
      const declaration = node.declaration
      needExportDefault = false
      if (
        declaration &&
        (declaration.type === 'ClassDeclaration' || declaration.type === 'ClassExpression')
      ) {
        const superClass = declaration.superClass
        if (superClass) {
          let hasCreateData = false
          astPath.traverse({
            ClassMethod (astPath) {
              if (astPath.get('key').isIdentifier({ name: '_createData' })) {
                hasCreateData = true
              }
            }
          })
          if (hasCreateData) {
            needExportDefault = true
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:astProcess.ts


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


示例8: Set

 let patterns = t.objectPattern(Array.from(new Set(propsKeys)).map(s =>
   t.objectProperty(t.identifier(s), t.identifier(s))
开发者ID:YangShaoQun,项目名称:taro,代码行数:2,代码来源:utils.ts



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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