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


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

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


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

 return arr.map(value => {
   if (typeof value === 'string') {
     return t.stringLiteral(value)
   }
   if (typeof value === 'number') {
     return t.numericLiteral(value)
   }
   if (typeof value === 'boolean') {
     return t.booleanLiteral(value)
   }
   if (Array.isArray(value)) {
     return convertArrayToAstExpression(value)
   }
   if (typeof value === 'object') {
     return t.objectExpression(convertObjectToAstExpression(value))
   }
   return t.nullLiteral()
 })
开发者ID:YangShaoQun,项目名称:taro,代码行数:18,代码来源:astConvert.ts

示例3:

 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

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

示例5: analyzeImportUrl

function analyzeImportUrl ({
  astPath,
  value,
  sourceFilePath,
  filePath,
  styleFiles,
  scriptFiles,
  jsonFiles,
  mediaFiles
}: IAnalyzeImportUrlOptions): void {
  const valueExtname = path.extname(value)
  const node = astPath.node
  const {
    nodeModulesPath,
    npmOutputDir,
    sourceDir,
    outputDir,
    npmConfig
  } = getBuildData()
  if (value.indexOf('.') === 0) {
    let importPath = path.resolve(path.dirname(sourceFilePath), value)
    importPath = resolveScriptPath(importPath)
    if (isFileToBePage(importPath)) {
      astPath.remove()
    } else {
      if (REG_SCRIPT.test(valueExtname) || REG_TYPESCRIPT.test(valueExtname)) {
        const vpath = path.resolve(sourceFilePath, '..', value)
        let fPath = value
        if (fs.existsSync(vpath) && vpath !== sourceFilePath) {
          fPath = vpath
        }
        if (scriptFiles.indexOf(fPath) < 0) {
          scriptFiles.push(fPath)
        }
      } else if (REG_JSON.test(valueExtname)) {
        const vpath = path.resolve(sourceFilePath, '..', value)
        if (jsonFiles.indexOf(vpath) < 0) {
          jsonFiles.push(vpath)
        }
        if (fs.existsSync(vpath)) {
          const obj = JSON.parse(fs.readFileSync(vpath).toString())
          const specifiers = node.specifiers
          let defaultSpecifier = null
          specifiers.forEach(item => {
            if (item.type === 'ImportDefaultSpecifier') {
              defaultSpecifier = item.local.name
            }
          })
          if (defaultSpecifier) {
            let objArr: t.NullLiteral | t.Expression = t.nullLiteral()
            if (Array.isArray(obj)) {
              objArr = t.arrayExpression(convertArrayToAstExpression(obj))
            } else {
              objArr = t.objectExpression(convertObjectToAstExpression(obj))
            }
            astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), objArr)]))
          }
        }
      } else if (REG_FONT.test(valueExtname) || REG_IMAGE.test(valueExtname) || REG_MEDIA.test(valueExtname)) {
        const vpath = path.resolve(sourceFilePath, '..', value)
        if (!fs.existsSync(vpath)) {
          printLog(processTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`)
          return
        }
        if (mediaFiles.indexOf(vpath) < 0) {
          mediaFiles.push(vpath)
        }
        const specifiers = node.specifiers
        let defaultSpecifier = null
        specifiers.forEach(item => {
          if (item.type === 'ImportDefaultSpecifier') {
            defaultSpecifier = item.local.name
          }
        })
        let showPath
        if (NODE_MODULES_REG.test(vpath)) {
          showPath = vpath.replace(nodeModulesPath, `/${npmConfig.name}`)
        } else {
          showPath = vpath.replace(sourceDir, '')
        }

        if (defaultSpecifier) {
          astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), t.stringLiteral(showPath.replace(/\\/g, '/')))]))
        } else {
          astPath.remove()
        }
      } else if (REG_STYLE.test(valueExtname)) {
        const stylePath = path.resolve(path.dirname(sourceFilePath), value)
        if (styleFiles.indexOf(stylePath) < 0) {
          styleFiles.push(stylePath)
        }
        astPath.remove()
      } else {
        let vpath = resolveScriptPath(path.resolve(sourceFilePath, '..', value))
        let outputVpath
        if (NODE_MODULES_REG.test(vpath)) {
          outputVpath = vpath.replace(nodeModulesPath, npmOutputDir)
        } else {
          outputVpath = vpath.replace(sourceDir, outputDir)
        }
//.........这里部分代码省略.........
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:astProcess.ts

示例6: parseAst


//.........这里部分代码省略.........
                  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
            if (declaration.id === null) {
              componentClassName = '_TaroComponentClass'
            } else if (declaration.id.name === 'App') {
开发者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: codeFrameError


//.........这里部分代码省略.........
                          value: p.value
                        })
                      } else if (key === 'observer') {
                        observeProps.push({
                          name: propKey,
                          observer: p.value
                        })
                      }
                      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
      }
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:script.ts

示例9: parsePage


//.........这里部分代码省略.........
                          value: p.value
                        })
                      } else if (key === 'observer') {
                        observeProps.push({
                          name: propKey,
                          observer: p.value
                        })
                      }
                      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
      }
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:script.ts

示例10: _rewriteImportMetaToBundleMeta

 private _rewriteImportMetaToBundleMeta(
     bundledImportMetaIdentifierName: string,
     moduleFile: babel.File,
     relativeUrl: FileRelativeUrl): babel.File {
   // Generate a stand-in for any local references to import.meta...
   // ```javascript
   // const bundledImportMeta = {
   //    ...import.meta,
   //    url: new URL(${ relativeUrl }, import.meta.url).href
   // };
   // ```
   // TODO(usergenic): Consider migrating this AST production mishmash into the
   // `ast` tagged template literal available like this:
   // https://github.com/Polymer/tools/blob/master/packages/build/src/babel-plugin-dynamic-import-amd.ts#L64
   const bundledImportMetaDeclaration = babel.variableDeclaration(
       //
       'const',
       [
         //
         babel.variableDeclarator(
             babel.identifier(bundledImportMetaIdentifierName),
             babel.objectExpression([
               babel.spreadProperty(babel.memberExpression(
                   babel.identifier('import'), babel.identifier('meta'))),
               babel.objectProperty(
                   babel.identifier('url'),
                   babel.memberExpression(
                       babel.newExpression(
                           babel.identifier('URL'),
                           [
                             //
                             babel.stringLiteral(relativeUrl),
                             babel.memberExpression(
                                 babel.memberExpression(
                                     babel.identifier('import'),
                                     babel.identifier('meta')),
                                 babel.identifier('url'))
                           ]),
                       babel.identifier('href')))
             ]))
       ]);
   const newModuleFile = clone(moduleFile);
   traverse(newModuleFile, {
     noScope: true,
     MetaProperty: {
       enter(path: NodePath<babel.MetaProperty>) {
         const metaProperty = path.node;
         if (metaProperty.meta.name !== 'import' &&
             metaProperty.property.name !== 'meta') {
           // We're specifically looking for instances of `import.meta` so
           // ignore any other meta properties.
           return;
         }
         const bundledImportMeta =
             babel.identifier(bundledImportMetaIdentifierName);
         path.replaceWith(bundledImportMeta);
       },
     },
   });
   newModuleFile.program.body.unshift(bundledImportMetaDeclaration);
   return newModuleFile;
 }
开发者ID:MehdiRaash,项目名称:tools,代码行数:62,代码来源:es6-rewriter.ts


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