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 rpetrich / swift-to-js / values.ts View on Github external
export function literal(value: LiteralValue, location?: LocationSource): ExpressionValue | VariableValue {
	if (typeof value === "boolean") {
		return expr(booleanLiteral(value), location);
	} else if (typeof value === "number") {
		return expr(numericLiteral(value), location);
	} else if (typeof value === "string") {
		return expr(stringLiteral(value), location);
	} else if (value === null) {
		return expr(nullLiteral(), location);
	} else if (Array.isArray(value)) {
		return expr(arrayExpression(value.map((element) => literal(element, location).expression)), location);
	} else if (typeof value === "object") {
		return expr(objectExpression(Object.keys(value).map((key) => {
			const expression = literal((value as LiteralMap)[key], location).expression;
			if (validIdentifier.test(key)) {
				return objectProperty(identifier(key), expression);
			} else {
				// Case where key is not a valid identifier
				return objectProperty(stringLiteral(key), expression, true);
			}
		})), location) as ExpressionValue;
	} else {
		throw new TypeError(`Expected to receive a valid literal type, instead got ${typeof value}`);
github framer / component-importer / src / babel.ts View on Github external
if (propsTypeDecl) {
                console.log(decl.id.name, propsTypeDecl.id.name)
                const comp: ComponentInfo = {
                    name: decl.id.name,
                    propsTypeInfo: typeAliasToTypeInfo(propsTypeDecl),
                }
                file.components.push(comp)
            }
            // console.log(decl.id.name, propsTypeName)
        }
        for (const st of file.parsed.program.body) {
            if (isExpressionStatement(st)) {
                const exp = st.expression
                if (isAssignmentExpression(exp)) {
                    const left = exp.left
                    if (isMemberExpression(left)) {
                        const prop = left.property
                        const obj = left.object
                        if (isIdentifier(obj) && isIdentifier(prop) && prop.name == "propTypes") {
                            const right = exp.right
                            if (isObjectExpression(right)) {
                                file.components.push({
                                    name: obj.name,
                                    propsTypeInfo: propTypesToTypeInfo(right),
                                })
                                // console.log(file.components[file.components.length - 1].propsTypeInfo.properties)
                            }
                        }
                    }
                }
            }
        }
github parcel-bundler / parcel / packages / core / parcel-bundler / src / scope-hoisting / concat.js View on Github external
exit(path) {
        if (!path.isReferenced()) {
          return;
        }

        let {object, property, computed} = path.node;
        if (
          !(
            t.isIdentifier(object) &&
            ((t.isIdentifier(property) && !computed) ||
              t.isStringLiteral(property))
          )
        ) {
          return;
        }

        let match = object.name.match(EXPORTS_RE);

        // If it's a $id$exports.name expression.
        if (match) {
          let name = t.isIdentifier(property) ? property.name : property.value;
          let {identifier} = packager.findExportModule(
            match[1],
            name,
            replacements,
          );
github alibaba / rax / packages / jsx-compiler / src / modules / condition.js View on Github external
function generateConditionValue(test, options) {
  let conditionValue;
  if (/Expression$/.test(test.type)) {
    conditionValue = t.jsxExpressionContainer(test);
  } else if (t.isStringLiteral(test)) {
    conditionValue = test;
  } else {
    // Other literal types or identifier.
    conditionValue = t.stringLiteral(createBinding(genExpression(test)));
    if (t.isIdentifier(test)) options.dynamicValue[test.name] = test;
  }
  return conditionValue;
}
github facebook / prepack / src / serializer / ResidualReactElementSerializer.js View on Github external
this._emitHoistedReactElement(
            value,
            id,
            reactElementAstNode,
            hoistedCreateElementIdentifier,
            originalCreateElementIdentifier
          );
        } else {
          // Note: it can be expected that we assign to the same variable multiple times
          // this is due to fact ReactElements are immutable objects and the fact that
          // when we inline/fold logic, the same ReactElements are referenced at different
          // points with different attributes. Given we can't mutate an immutable object,
          // we instead create new objects and assign to the same binding
          if (reactElement.declared) {
            this.residualHeapSerializer.emitter.emit(
              t.expressionStatement(t.assignmentExpression("=", id, reactElementAstNode))
            );
          } else {
            reactElement.declared = true;
            this.residualHeapSerializer.emitter.emit(
              t.variableDeclaration("var", [t.variableDeclarator(id, reactElementAstNode)])
            );
          }
        }
      },
      this.residualHeapSerializer.emitter.getBody()
github awto / effectfuljs / packages / transducers / src / trace.js View on Github external
export function cg(ast, opts = {}) {
  var res;
  if (ast == null) {
    // console.error("")
    return "";
  }
  try {
    if (Array.isArray(ast)) {
      ast =
        ast.length > 0 && T.isExpression(ast[0])
          ? T.sequenceExpression(ast)
          : T.blockStatement(ast);
    }
    res = generate(ast, opts, "").code;
  } catch (e) {
    if (ast.type != null) console.log("ERROR:", e.stack);
  }
  if (res != null) {
    return res;
  }
  return "!!" + opts.compact
    ? JSON.stringify(ast, defaultReplacer)
    : JSON.stringify(ast, defaultReplacer, 2);
}
github awto / effectfuljs / packages / core / src / kit / trace.js View on Github external
export function cg(ast, opts = {}) {
  var res;
  if (ast == null) {
    // console.error("")
    return "";
  }
  try {
    if (Array.isArray(ast)) {
      ast =
        ast.length > 0 && T.isExpression(ast[0])
          ? T.sequenceExpression(ast)
          : T.blockStatement(ast);
    }
    res = generate(ast, opts).code;
  } catch (e) {
    if (ast.type != null) console.error(e.stack);
  }
  if (res != null) return res;
  return "!!" + opts.compact
    ? JSON.stringify(ast)
    : JSON.stringify(ast, null, 2);
}
github zhangdaren / miniprogram-to-uniapp / src / wx2uni / jsHandle.js View on Github external
// console.log(logStr);

									//设置默认值
									let initialValue;
									switch (value.type) {
										case "BooleanLiteral":
											initialValue = t.booleanLiteral(false);
											break;
										case "NumericLiteral":
											initialValue = t.numericLiteral(0);
											break;
										case "ArrayExpression":
											initialValue = t.arrayExpression();
											break;
										case "ObjectExpression":
											initialValue = t.objectExpression([]);
											break;
										default:
											//其余全是空
											initialValue = t.stringLiteral("");
											break;
									}

									vistors.data.handle(t.objectProperty(t.identifier(name), initialValue));
									dataJson[name] = name;
								} else {
									//TODO:
									//如果props有个变量abc,使用this.setData({abc:1})会报错,但在小程序里是正确的,
									//如果要改的话,要用一个中间变量,并且把页面里所有的地方都要替换,工作量有点繁琐。
								}
							}
						}
github peakchen90 / babel-plugin-react-directives / src / directives / show.js View on Github external
find(attr, setValue) {
      const attrName = attrUtil(attr).name();
      const valueExpr = attrUtil(attr).valueExpr();

      /* istanbul ignore next: print warn info */
      if (attrName === 'style') {
        if (t.isStringLiteral(valueExpr)) {
          codeFrameWarn(
            attr,
            'The `style` prop expected a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + \'em\'}}'
          );
        } else {
          setValue(t.objectExpression([
            t.objectProperty(
              t.identifier('style'),
              valueExpr
            )
          ]));
        }
        return true;
      }

      /* istanbul ignore next: print warn info */
      if (/^(style)$/i.test(attrName)) {
        codeFrameWarn(
          attr,
          `Non-lowercase \`style\` prop will be ignored, when use \`${DIRECTIVES.SHOW}\``
        );
        return true;
github alibaba / rax / packages / jsx-compiler / src / modules / components.js View on Github external
enableScopeSlot = true;
      }
    },
  });

  const dynamicValue = transformTemplate(jsxEl, slotName);
  // Remove dynamicValue that created by params.
  Object.keys(dynamicValue).forEach(key => {
    if (params.hasOwnProperty(key) || /^props\./.test(key))
      delete dynamicValue[key];
  });

  if (enableScopeSlot) {
    // Add scope slot
    jsxEl.openingElement.attributes.push(
      t.jsxAttribute(t.jsxIdentifier('slot-scope'), t.stringLiteral('props')),
    );
  }

  // Add slot attr
  jsxEl.openingElement.attributes.push(
    t.jsxAttribute(t.jsxIdentifier('slot'), t.stringLiteral(slotName)),
  );

  return { dynamicValue, node: jsxEl };
}