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

TypeScript babel-template.default函数代码示例

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

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



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

示例1: parseAst

export function parseAst (
  type: PARSE_AST_TYPE,
  ast: t.File,
  depComponents: IComponentObj[],
  sourceFilePath: string,
  filePath: string,
  npmSkip: boolean = false
): IParseAstReturn {
  const styleFiles: string[] = []
  const scriptFiles: string[] = []
  const jsonFiles: string[] = []
  const mediaFiles: string[] = []

  const {
    appPath,
    nodeModulesPath,
    npmOutputDir,
    sourceDir,
    outputDir,
    buildAdapter,
    constantsReplaceList,
    isProduction,
    npmConfig,
    alias: pathAlias,
    compileInclude,
    projectConfig
  } = getBuildData()
  const notExistNpmList = getNotExistNpmList()
  const taroMiniAppFramework = `@tarojs/taro-${buildAdapter}`
  let configObj: IConfig = {}
  let componentClassName: string = ''
  let taroJsReduxConnect: string = ''
  let taroImportDefaultName
  let needExportDefault = false
  let exportTaroReduxConnected: string | null = null
  const isQuickApp = buildAdapter === BUILD_TYPES.QUICKAPP
  const cannotRemoves = [taroJsFramework, 'react', 'nervjs']
  let hasComponentDidHide
  let hasComponentDidShow
  let hasComponentWillMount
  let hasEnablePageScroll
  if (isQuickApp) {
    cannotRemoves.push(taroJsComponents)
  }
  const taroSelfComponents = new Set<string>()
  ast = babel.transformFromAst(ast, '', {
    plugins: [
      [require('babel-plugin-danger-remove-unused-import'), { ignore: cannotRemoves }],
      [require('babel-plugin-transform-define').default, constantsReplaceList]
    ]
  }).ast as t.File
  traverse(ast, {
    ClassDeclaration (astPath) {
      const node = astPath.node
      let hasCreateData = false
      if (node.superClass) {
        astPath.traverse({
          ClassMethod (astPath) {
            if (astPath.get('key').isIdentifier({ name: '_createData' })) {
              hasCreateData = true
            }
          }
        })
        if (hasCreateData) {
          needExportDefault = true
          astPath.traverse({
            ClassMethod (astPath) {
              const node = astPath.node
              if (node.kind === 'constructor') {
                astPath.traverse({
                  ExpressionStatement (astPath) {
                    const node = astPath.node
                    if (node.expression &&
                      node.expression.type === 'AssignmentExpression' &&
                      node.expression.operator === '=') {
                      const left = node.expression.left
                      if (left.type === 'MemberExpression' &&
                        left.object.type === 'ThisExpression' &&
                        left.property.type === 'Identifier' &&
                        left.property.name === 'config') {
                        configObj = traverseObjectNode(node.expression.right, buildAdapter)
                      }
                    }
                  }
                })
              }
            }
          })
          if (node.id === null) {
            componentClassName = '_TaroComponentClass'
            astPath.replaceWith(
              t.classDeclaration(
                t.identifier(componentClassName),
                node.superClass as t.Expression,
                node.body as t.ClassBody,
                node.decorators as t.Decorator[] || []
              )
            )
          } else if (node.id.name === 'App') {
            componentClassName = '_App'
//.........这里部分代码省略.........
开发者ID:YangShaoQun,项目名称:taro,代码行数:101,代码来源:astProcess.ts


示例2: template

 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 })
     )
   }
 }
开发者ID:YangShaoQun,项目名称:taro,代码行数:31,代码来源:utils.ts


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


示例4: template

 iconPaths.forEach(item => {
   const iconPath = item.startsWith('/') ? item : `/${item}`
   const iconName = _.camelCase(iconPath)
   const importIcon = template(
     `import ${iconName} from '.${iconPath}'`,
     babylonConfig as any
   )()
   node.body.unshift(importIcon as any)
 })
开发者ID:YangShaoQun,项目名称:taro,代码行数:9,代码来源:transformJS.ts


示例5: pascalCase

 imports.forEach(({ name, ast }) => {
   const importName = pascalCase(name)
   if (componentClassName === importName) {
     return
   }
   const importPath = path.join(self.importsDir, importName + '.js')
   if (!self.hadBeenBuiltImports.has(importPath)) {
     self.hadBeenBuiltImports.add(importPath)
     self.writeFileToTaro(importPath, prettier.format(generateMinimalEscapeCode(ast), prettierJSConfig))
   }
   lastImport.insertAfter(template(`import ${importName} from '${promoteRelativePath(path.relative(outputFilePath, importPath))}'`, babylonConfig)())
 })
开发者ID:YangShaoQun,项目名称:taro,代码行数:12,代码来源:index.ts


示例6: template

 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 })
     )
   }
 }
开发者ID:topud,项目名称:taro,代码行数:17,代码来源:utils.ts


示例7: function

 StringLiteral: function(path: traverse.NodePath<types.StringLiteral>) {
   var node = path.node as any;
   if (!node.macro || !node.value) {
       return;
   }
   var buildArgs: any = {}, macro: string = node.value;
   try {
     var args = node.args;
     for (var i = 0; i < args.length; i++) {
         buildArgs["$" + i] = args[i];
     }
     macro = macro
         // Replace spread aguments like in `$0($1...)`
         .replace(/\$(\d+)\.\.\./, function (m, i) {
             var rep = [], j = parseInt(i);
             for (; j < args.length; j++) {
                 rep.push("$" + j);
             }
             return rep.join(",");
         })
         // Replace conditional arguments like in `/$0/g{{$1?i:}}{{$2?m:}}`
         .replace(/\{\{\$(\d+)\?(.*?)\:(.*?)\}\}/g, function (_, g1, g2, g3) {
             var i = parseInt(g1);
             return i < args.length && args[i].value ? g2 : g3;
         })
         // Replace optional arguments like in `$0[$1]{{=$2}}`
         .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, function (_, g1, g2) {
             var i = parseInt(g2);
             return i < args.length ? g1 : "";
         });
     var buildMacro = template(macro);
     path.replaceWithMultiple(buildMacro(buildArgs));
   }
   catch (err) {
     err.message =
       "BABEL ERROR: Failed to parse macro: " + macro + "\n" +
       "MACRO ARGUMENTS: " + Object.getOwnPropertyNames(buildArgs).join() + "\n" +
       err.message;
     throw err;
   }
 }
开发者ID:7sharp9,项目名称:Fable,代码行数:41,代码来源:babelPlugins.ts


示例8: buildFullPathThisPropsRef

function buildFullPathThisPropsRef (id: t.Identifier, memberIds: string[], path: NodePath<t.Node>) {
  const scopePath = findDeclarationScope(path, id)
  const binding = scopePath.scope.getOwnBinding(id.name)
  if (binding) {
    const bindingPath = binding.path
    if (bindingPath.isVariableDeclarator()) {
      const dclId = bindingPath.get('id')
      const dclInit = bindingPath.get('init')
      let dclInitIds: string[] = []
      if (dclInit.isMemberExpression()) {
        dclInitIds = getIdsFromMemberProps(dclInit.node)
        if (dclId.isIdentifier()) {
          memberIds.shift()
        }
        if (dclInitIds[0] === 'this' && dclInitIds[1] === 'props') {
          return template(dclInitIds.concat(memberIds).join('.'))().expression
        }
      }
    }
  }
}
开发者ID:topud,项目名称:taro,代码行数:21,代码来源:index.ts


示例9: convertSourceStringToAstExpression

export function convertSourceStringToAstExpression (str: string, opts: object = {}) {
  return template(str, Object.assign({}, babylonConfig, opts))()
}
开发者ID:YangShaoQun,项目名称:taro,代码行数:3,代码来源:astConvert.ts



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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