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

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

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

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



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

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


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


示例3: prepareBundleModule

/**
 * Generate code containing import statements to all bundled modules and
 * export statements to re-export their namespaces and exports.
 *
 * Example: a bundle containing files `module-a.js` and `module-b.js` would
 * result in a prepareBundleModule result like:
 *
 *     import * as $moduleA from './module-a.js';
 *     import * as $moduleB from './module-b.js';
 *     import $moduleBDefault from './module-b.js';
 *     export {thing1, thing2} from './module-a.js';
 *     export {thing3} from './module-b.js';
 *     export {$moduleA, $moduleB, $moduleBDefault};
 */
async function prepareBundleModule(
    bundler: Bundler, manifest: BundleManifest, assignedBundle: AssignedBundle):
    Promise<string> {
      let bundleSource = babel.program([]);
      const sourceAnalysis =
          await bundler.analyzer.analyze([...assignedBundle.bundle.files]);
      for (const sourceUrl of [...assignedBundle.bundle.files].sort()) {
        const rebasedSourceUrl =
            ensureLeadingDot(bundler.analyzer.urlResolver.relative(
                stripUrlFileSearchAndHash(assignedBundle.url), sourceUrl));
        const moduleDocument = getAnalysisDocument(sourceAnalysis, sourceUrl);
        const moduleExports = getModuleExportNames(moduleDocument);
        const starExportName =
            getOrSetBundleModuleExportName(assignedBundle, sourceUrl, '*');
        bundleSource.body.push(babel.importDeclaration(
            [babel.importNamespaceSpecifier(babel.identifier(starExportName))],
            babel.stringLiteral(rebasedSourceUrl)));
        if (moduleExports.size > 0) {
          bundleSource.body.push(babel.exportNamedDeclaration(
              undefined, [babel.exportSpecifier(
                             babel.identifier(starExportName),
                             babel.identifier(starExportName))]));
          bundleSource.body.push(babel.exportNamedDeclaration(
              undefined,
              [...moduleExports].map(
                  (e) => babel.exportSpecifier(
                      babel.identifier(e),
                      babel.identifier(getOrSetBundleModuleExportName(
                          assignedBundle, sourceUrl, e)))),
              babel.stringLiteral(rebasedSourceUrl)));
        }
      }
      const {code} = generate(bundleSource);
      return code;
    }
开发者ID:Polymer,项目名称:vulcanize,代码行数:49,代码来源:es6-module-bundler.ts


示例4: rewriteExportAllToNamedExports

 rewriteExportAllToNamedExports(node: babel.Node, analysis: Analysis) {
   traverse(node, {
     noScope: true,
     ExportAllDeclaration: {
       enter(path: NodePath<babel.ExportAllDeclaration>) {
         const exportAllDeclaration = path.node;
         const sourceUrl =
             babel.isStringLiteral(exportAllDeclaration.source) &&
             exportAllDeclaration.source.value;
         if (!sourceUrl) {
           return;
         }
         const sourceDocument = getAnalysisDocument(analysis, sourceUrl);
         const documentExports = sourceDocument.getFeatures({kind: 'export'});
         const specifiers: babel.ExportSpecifier[] = [];
         for (const documentExport of documentExports) {
           for (const exportIdentifier of documentExport.identifiers) {
             const identifierValue = exportIdentifier.valueOf();
             // It does not appear that `export * from` should re-export
             // the default module export of a module.
             if (identifierValue !== 'default') {
               specifiers.push(babel.exportSpecifier(
                   babel.identifier(identifierValue),
                   babel.identifier(identifierValue)));
             }
           }
         }
         const namedExportDeclaration = babel.exportNamedDeclaration(
             undefined, specifiers, babel.stringLiteral(sourceUrl));
         rewriteObject(exportAllDeclaration, namedExportDeclaration);
       }
     }
   });
 }
开发者ID:Polymer,项目名称:tools,代码行数:34,代码来源:es6-rewriter.ts


示例5: 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: (p) => {
          const { id, init } = p.node
          if (t.isIdentifier(id)) {
            const newId = scope.generateDeclaredUidIdentifier('$' + id.name)
            refIds.forEach((refId) => {
              if (refId.name === variableName && !variableName.startsWith('_$')) {
                refIds.delete(refId)
              }
            })
            variableName = newId.name
            refIds.add(t.identifier(variableName))
            blockStatement.scope.rename(id.name, newId.name)
            p.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 {
        func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr))
      }
    }
  }
  const id = t.identifier(variableName)
  expression.replaceWith(id)
  return id
}
开发者ID:topud,项目名称:taro,代码行数:60,代码来源:utils.ts


示例6:

 specifiers.forEach((item, index) => {
   if ((item as t.ImportSpecifier).imported && taroApis.indexOf((item as t.ImportSpecifier).imported.name) >= 0) {
     taroApisSpecifiers.push(
       t.importSpecifier(t.identifier((item as t.ImportSpecifier).local.name), t.identifier((item as t.ImportSpecifier).imported.name)))
     specifiers.splice(index, 1)
   }
 })
开发者ID:YangShaoQun,项目名称:taro,代码行数:7,代码来源:transformJS.ts


示例7:

 path.node.specifiers.forEach((s, index, specs) => {
   if (s.local.name === 'Provider') {
     specs.splice(index, 1)
     specs.push(
       t.importSpecifier(t.identifier('setStore'), t.identifier('setStore'))
     )
   }
 })
开发者ID:teachat8,项目名称:taro,代码行数:8,代码来源:index.ts


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


示例9:

 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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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