當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript babel-types.objectProperty函數代碼示例

本文整理匯總了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;未經允許,請勿轉載。