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


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

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


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

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

示例2: buildConstVariableDeclaration

export function buildConstVariableDeclaration (
  variableName: string,
  expresion: t.Expression
) {
  return t.variableDeclaration('const', [
    t.variableDeclarator(t.identifier(variableName), expresion)
  ])
}
开发者ID:topud,项目名称:taro,代码行数:8,代码来源:utils.ts

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

示例4: parseAst


//.........这里部分代码省略.........
        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') {
              componentClassName = '_App'
            } else {
              componentClassName = declaration.id.name
            }
            const isClassDcl = declaration.type === 'ClassDeclaration'
            const classDclProps = [t.identifier(componentClassName), superClass, declaration.body, declaration.decorators || []]
            astPath.replaceWith(isClassDcl ? t.classDeclaration.apply(null, classDclProps) : t.classExpression.apply(null, classDclProps))
          }
        }
      } else if (declaration.type === 'CallExpression') {
        const callee = declaration.callee
        if (callee && callee.type === 'CallExpression') {
          const subCallee = callee.callee
          if (subCallee.type === 'Identifier' && subCallee.name === taroJsReduxConnect) {
            const args = declaration.arguments as t.Identifier[]
            if (args.length === 1 && args[0].name === componentClassName) {
              needExportDefault = true
              exportTaroReduxConnected = `${componentClassName}__Connected`
              astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(`${componentClassName}__Connected`), t.callExpression(declaration.callee as t.Expression, declaration.arguments as Array<t.Expression | t.SpreadElement>))]))
            }
          }
        }
      } else if (declaration.type === 'Identifier') {
        const name = declaration.name
        if (name === componentClassName || name === exportTaroReduxConnected) {
          needExportDefault = true
          astPath.remove()
        }
      }
    },

    ExportNamedDeclaration (astPath) {
      const node = astPath.node
      const source = node.source
      if (source && source.type === 'StringLiteral') {
        const value = source.value
        analyzeImportUrl({ astPath, value, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
      }
    },

    ExportAllDeclaration (astPath) {
      const node = astPath.node
      const source = node.source
      if (source && source.type === 'StringLiteral') {
        const value = source.value
        analyzeImportUrl({ astPath, value, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles })
      }
    },

    Program: {
      exit (astPath) {
开发者ID:YangShaoQun,项目名称:taro,代码行数:67,代码来源:astProcess.ts

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

示例6: generateAnonymousState

export function generateAnonymousState (
  scope: Scope,
  expression: NodePath<t.Expression>,
  refIds: Set<t.Identifier>,
  isLogical?: boolean
) {
  let variableName = `anonymousState_${scope.generateUid()}`
  let statementParent = expression.getStatementParent()
  if (!statementParent) {
    throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。')
  }
  const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement())
  const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)) as NodePath<t.CallExpression>
  const ifExpr = jsx.findParent(p => p.isIfStatement())
  const blockStatement = jsx.findParent(p => p.isBlockStatement() && p.parentPath === ifExpr) as NodePath<t.BlockStatement>
  const expr = setParentCondition(jsx, cloneDeep(expression.node))
  if (!callExpr) {
    refIds.add(t.identifier(variableName))
    statementParent.insertBefore(
      buildConstVariableDeclaration(variableName, expr)
    )
    if (blockStatement && blockStatement.isBlockStatement()) {
      blockStatement.traverse({
        VariableDeclarator: (path) => {
          const { id, init } = path.node
          const isArrowFunctionInJSX = path.findParent(p => p.isJSXAttribute() ||
            (
              p.isAssignmentExpression() && t.isMemberExpression(p.node.left) && t.isThisExpression(p.node.left.object)
                && t.isIdentifier(p.node.left.property) && p.node.left.property.name.startsWith('')
            )
          )
          if (isArrowFunctionInJSX) {
            return
          }
          if (t.isIdentifier(id) && !id.name.startsWith(LOOP_STATE)) {
            const newId = scope.generateDeclaredUidIdentifier('$' + id.name)
            refIds.forEach((refId) => {
              if (refId.name === variableName && !variableName.startsWith('_$')) {
                refIds.delete(refId)
              }
            })
            variableName = newId.name
            if (Adapter.type === Adapters.quickapp && variableName.startsWith('_$')) {
              const newVarName = variableName.slice(2)
              scope.rename(variableName, newVarName)
              variableName = newVarName
            }
            refIds.add(t.identifier(variableName))
            blockStatement.scope.rename(id.name, newId.name)
            path.parentPath.replaceWith(
              template('ID = INIT;')({ ID: newId, INIT: init })
            )
          }
        }
      })
    }
  } else {
    variableName = `${LOOP_STATE}_${callExpr.scope.generateUid()}`
    const func = callExpr.node.arguments[0]
    if (t.isArrowFunctionExpression(func)) {
      if (!t.isBlockStatement(func.body)) {
        func.body = t.blockStatement([
          buildConstVariableDeclaration(variableName, expr),
          t.returnStatement(func.body)
        ])
      } else {
        if (ifExpr && ifExpr.isIfStatement() && ifExpr.findParent(p => p === callExpr)) {
          const consequent = ifExpr.get('consequent')
          const test = ifExpr.get('test')
          if (consequent.isBlockStatement()) {
            if (jsx === test || jsx.findParent(p => p === test)) {
              func.body.body.unshift(buildConstVariableDeclaration(variableName, expr))
            } else {
              func.body.body.unshift(t.variableDeclaration('let', [t.variableDeclarator(t.identifier(variableName), t.nullLiteral())]))
              consequent.node.body.push(t.expressionStatement(t.assignmentExpression(
                '=',
                t.identifier(variableName),
                expr
              )))
            }
          } else {
            throw codeFrameError(consequent.node, 'if 表达式的结果必须由一个花括号包裹')
          }
        } else {
          func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr))
        }
      }
    }
  }
  const id = t.identifier(variableName)
  expression.replaceWith(id)
  return id
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:93,代码来源:utils.ts

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