How to use babel-types - 10 common examples

To help you get started, we’ve selected a few babel-types examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Tencent / omi / packages / omip / taro-transformer-wx / __tests__ / utils.ts View on Github external
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 +
    ';' + `new Test(${props})`

  code = internalFunction + code
github NativeScript / android-runtime / test-app / build-tools / jsparser / visitors / es5-visitors.js View on Github external
try {
            extendClass = _getArgumentFromNodeAsString(path, 5, config)
        } catch (e) {
            config.logger.warn(e.message)
            return;
        }

        var overriddenMethodNames = _getOverriddenMethodsTypescript(path, 3);

        var extendPath = _getParent(path, 3, config);
        var declaredClassName = "";

        var typescriptClassExtendSuperCallLocation = getTypeScriptExtendSuperCallLocation(extendPath, config);
        var extendParent = _getParent(path, 1, config);

        if (types.isCallExpression(extendParent)) {
            declaredClassName = extendParent.node.arguments[0].name;
        }

        var decorateNodes = traverseForDecorate(path, config, 3);

        var isDecoratedWithExtend = false,
            customExtendDecoratorName,
            customExtendDecoratorValue,
            implementedInterfaces = [];

        if (!decorateNodes) {
            // 7 -> Takes 7 levels up to get to the scope where the class is declared
            decorateNodes = traverseForDecorateSpecial(path, config, 7);
        }

        if (decorateNodes) {
github Polymer / polymer-bundler / src / bundle-js-module.ts View on Github external
// Transform:
      //   import('./some/module.js')
      // Into:
      //   import('./bundle_1.js')
      //       .then(({ $bundled$some$module }) => $bundled$some$module)
      const importCallExpression = babelUtils.getParentNode(astRoot, jsImport);
      if (!importCallExpression ||
          !babel.isCallExpression(importCallExpression)) {
        // TODO(usergenic): This log should be a real error or warning or
        // something.
        console.log(
            'CAN NOT INSERT CODE BECAUSE CAN NOT FIND PARENT OF IMPORT IN DOCUMENT AST');
        continue;
      }
      const importCallArgument = importCallExpression.arguments[0]!;
      if (!babel.isStringLiteral(importCallArgument)) {
        console.log(
            'CAN NOT FIGURE OUT WHERE THE DYNAMIC IMPORT IS PULLING FROM.  I ONLY UNDERSTAND STRING LITERALS');
        continue;
      }
      const sourceUrl = importCallArgument.value;
      const resolvedSourceUrl =
          urlLib.resolve(docBundle.url, sourceUrl) as ResolvedUrl;
      const sourceBundle = bundleManifest.getBundleForFile(resolvedSourceUrl);
      if (sourceBundle && sourceBundle.url !== resolvedSourceUrl) {
        const exportedName = getOrSet(
            docBundle.bundle.exportedJsModules,
            resolvedSourceUrl,
            () => exportedJsModuleNameFn(sourceBundle.url, resolvedSourceUrl));

        importCallExpression.arguments[0] = babel.stringLiteral(
            urlUtils.relativeUrl(docBundle.url, sourceBundle.url));
github Polymer / polymer-bundler / src / bundle-js-module.ts View on Github external
if (duplicateJsImportSpecifier) {
          importDeclarationContainerArray.splice(
              importDeclarationContainerArray.indexOf(jsImport), 1);
        }
      }
    }
    // Dynamic Import
    if (jsImport.type === 'Import') {
      // Transform:
      //   import('./some/module.js')
      // Into:
      //   import('./bundle_1.js')
      //       .then(({ $bundled$some$module }) => $bundled$some$module)
      const importCallExpression = babelUtils.getParentNode(astRoot, jsImport);
      if (!importCallExpression ||
          !babel.isCallExpression(importCallExpression)) {
        // TODO(usergenic): This log should be a real error or warning or
        // something.
        console.log(
            'CAN NOT INSERT CODE BECAUSE CAN NOT FIND PARENT OF IMPORT IN DOCUMENT AST');
        continue;
      }
      const importCallArgument = importCallExpression.arguments[0]!;
      if (!babel.isStringLiteral(importCallArgument)) {
        console.log(
            'CAN NOT FIGURE OUT WHERE THE DYNAMIC IMPORT IS PULLING FROM.  I ONLY UNDERSTAND STRING LITERALS');
        continue;
      }
      const sourceUrl = importCallArgument.value;
      const resolvedSourceUrl =
          urlLib.resolve(docBundle.url, sourceUrl) as ResolvedUrl;
      const sourceBundle = bundleManifest.getBundleForFile(resolvedSourceUrl);
github Tencent / omi / packages / cax-omip / scripts / taro-transformer-wx / lib / src / render.js View on Github external
MemberExpression(path) {
                                const { object, property } = path.node;
                                if (t.isThisExpression(object) && t.isIdentifier(property, { name: 'data' })) {
                                    if (path.parentPath.isMemberExpression() && path.parentPath.parentPath.isMemberExpression()) {
                                        // tslint:disable-next-line
                                        console.warn(utils_1.codeFrameError(path.parentPath.parentPath.node, `在循环中使用 this.data.xx.xx 可能会存在问题,请给 xx 起一个别名,例如 const { xx } = this.data`));
                                    }
                                }
                            }
                        });
                        const originalProp = t.objectProperty(t.identifier(constant_1.LOOP_ORIGINAL), t.memberExpression(t.identifier(item.name), t.identifier(constant_1.LOOP_ORIGINAL)));
                        properties.push(originalProp);
                        body.unshift(t.expressionStatement(t.assignmentExpression('=', t.identifier(item.name), t.objectExpression([
                            t.objectProperty(t.identifier(constant_1.LOOP_ORIGINAL), t.callExpression(t.identifier(constant_1.INTERNAL_GET_ORIGNAL), [t.identifier(item.name)]))
                        ]))));
                        const returnStatement = t.returnStatement(properties.length ? t.objectExpression(properties) : item);
                        const parentCallee = callee.findParent(c => utils_1.isArrayMapCallExpression(c));
                        if (utils_1.isArrayMapCallExpression(parentCallee)) {
                            const [func] = parentCallee.node.arguments;
                            const { object } = callee.node.callee;
                            if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) {
                                const funcBody = func.body;
                                if (t.isBlockStatement(funcBody)) {
                                    if (t.isIdentifier(object) || t.isMemberExpression(object)) {
                                        const variableName = `${constant_1.LOOP_CALLEE}_${this.incrementCalleeId()}`;
                                        funcBody.body.splice(funcBody.body.length - 1, 0, utils_1.buildConstVariableDeclaration(variableName, utils_1.setParentCondition(component, callee.node, true)));
                                        const iterator = func.params[0];
                                        component.node.openingElement.attributes.forEach(attr => {
                                            if (attr.name.name === adapter_1.Adapter.for && t.isIdentifier(iterator)) {
                                                attr.value = t.jSXExpressionContainer(t.memberExpression(iterator, t.identifier(variableName)));
                                            }
                                        });
github Tencent / omi / packages / mps / _scripts / jsx2wxml / index.js View on Github external
TemplateLiteral(path) {
            const nodes = [];
            const { quasis, expressions } = path.node;
            let index = 0;
            if (path.parentPath.isTaggedTemplateExpression()) {
                return;
            }
            for (const elem of quasis) {
                if (elem.value.cooked) {
                    nodes.push(t.stringLiteral(elem.value.cooked));
                }
                if (index < expressions.length) {
                    const expr = expressions[index++];
                    if (!t.isStringLiteral(expr, { value: '' })) {
                        nodes.push(expr);
                    }
                }
            }
            // + 号连接符必须保证第一和第二个 node 都是字符串
            if (!t.isStringLiteral(nodes[0]) && !t.isStringLiteral(nodes[1])) {
                nodes.unshift(t.stringLiteral(''));
            }
            let root = nodes[0];
            for (let i = 1; i < nodes.length; i++) {
                root = t.binaryExpression('+', root, nodes[i]);
            }
github trivago / babel-plugin-cloudinary / lib / index.js View on Github external
return allPluginParameters[param];
      } else if (PLUGIN_PARAMETERS[param].default && PLUGIN_PARAMETERS[param].defaultType) {
        const babelConstructor = t[PLUGIN_PARAMETERS[param].defaultType];

        return babelConstructor(PLUGIN_PARAMETERS[param].default);
      }
    });
  const expressions = [...baseExpressions, ...astHelpers.filterExpressions(extraExpressions), t.stringLiteral("")];
  const quasis = [...baseQuasis, ...Object.keys(extraExpressions).map(() => astHelpers.templateElement(""))];

  // keep pairing between expressions and quasis with empty literals
  if (expressions.length < quasis.length) {
    const offset = quasis.length - expressions.length;

    for (let i = 0; i < offset; i++) {
      expressions.push(t.stringLiteral(""));
    }
  }

  path.replaceWith(t.expressionStatement(t.templateLiteral(quasis, expressions)));
}
github Tencent / omi / packages / omip / taro-transformer-wx / src / index.ts View on Github external
}
      }

      if (name.name.startsWith('on')) {
        if (exprPath.isReferencedIdentifier()) {
          const ids = [expr.name]
          const fullPath = buildFullPathThisPropsRef(expr, ids, path)
          if (fullPath) {
            exprPath.replaceWith(fullPath)
          }
        }

        if (exprPath.isReferencedMemberExpression()) {
          const id = findFirstIdentifierFromMemberExpression(expr)
          const ids = getIdsFromMemberProps(expr)
          if (t.isIdentifier(id)) {
            const fullPath = buildFullPathThisPropsRef(id, ids, path)
            if (fullPath) {
              exprPath.replaceWith(fullPath)
            }
          }
        }

        // @TODO: bind 的处理待定
      }
    },
    ImportDeclaration (path) {
github Tencent / omi / packages / mps-ts / _scripts / jsx2wxml / loop-component.js View on Github external
caller.getStatementParent().insertBefore(utils_1.buildConstVariableDeclaration(variableName, ary));
                                    ary = t.identifier(variableName);
                                }
                                jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.for, t.jSXExpressionContainer(ary));
                                const [func] = caller.node.arguments;
                                if (t.isFunctionExpression(func) ||
                                    t.isArrowFunctionExpression(func)) {
                                    const [item, index] = func.params;
                                    if (t.isIdentifier(item)) {
                                        jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral(item.name));
                                        loopScopes.add(item.name);
                                    }
                                    else {
                                        jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral('__item'));
                                    }
                                    if (t.isIdentifier(index)) {
                                        jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forIndex, t.stringLiteral(index.name));
                                        loopScopes.add(index.name);
                                    }
                                    caller.replaceWith(jsxElementPath.node);
                                    if (statementParent) {
                                        const name = utils_1.findIdentifierFromStatement(statementParent.node);
                                        // setTemplate(name, path, templates)
                                        name && templates.set(name, jsxElementPath.node);
                                    }
                                }
                            }
                        }
                    }
                    else {
                        const ifStatement = parentPath.findParent(p => p.isIfStatement());
                        const blockStatement = parentPath.findParent(p => p.isBlockStatement());
github Tencent / omi / packages / cax-omip / scripts / taro-transformer-wx / lib / src / render.js View on Github external
utils_1.newJSXIfAttr(block, test);
                    jsx_1.setJSXAttr(block2, adapter_1.Adapter.else);
                    block2.children = [t.jSXExpressionContainer(alternate)];
                    const parentBlock = jsx_1.buildBlockElement();
                    parentBlock.children = [block, block2];
                    parentPath.replaceWith(parentBlock);
                }
                if (statementParent) {
                    const name = utils_1.findIdentifierFromStatement(statementParent.node);
                    utils_1.setTemplate(name, jsxElementPath, this.templates);
                    // name && templates.set(name, path.node)
                }
            }
            else if (this.isLiteralOrUndefined(consequent) && t.isJSXElement(alternate)) {
                const { value, confident } = parentPath.get('consequent').evaluate();
                if (confident && !value || t.isIdentifier({ name: 'undefined' })) {
                    utils_1.newJSXIfAttr(block, utils_1.reverseBoolean(test));
                    block.children = [jsxElementPath.node];
                    // newJSXIfAttr(jsxElementPath.node, test)
                    parentPath.replaceWith(block);
                }
                else {
                    const block2 = jsx_1.buildBlockElement();
                    block.children = [t.jSXExpressionContainer(consequent)];
                    utils_1.newJSXIfAttr(block, test);
                    jsx_1.setJSXAttr(block2, adapter_1.Adapter.else);
                    block2.children = [alternate];
                    const parentBlock = jsx_1.buildBlockElement();
                    parentBlock.children = [block, block2];
                    parentPath.replaceWith(parentBlock);
                }
                if (statementParent) {