@babel/types#jsxOpeningElement TypeScript Examples

The following examples show how to use @babel/types#jsxOpeningElement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: img.ts    From react-optimized-image with MIT License 6 votes vote down vote up
transformImgComponent = (types: Babel['types'], path: NodePath<JSXElement>): void => {
  // abort if it has already the rawSrc attribute
  if (getAttribute(path, 'rawSrc')) {
    return;
  }

  // get src attribute
  const src = getAttribute(path, 'src');
  const requireArgs = src ? getRequireArguments(types, src) : undefined;

  if (!src || !requireArgs) {
    return;
  }

  const config = buildConfig(types, path);

  const query: Record<string, string> = {};

  // add boolean queries
  ['inline', 'url', 'original'].forEach((attr) => {
    if ((config as Record<string, unknown>)[attr] === true) {
      query[attr] = '';
    }
  });

  // transfer original src attribute if a new query param needs to be set
  if (Object.keys(query).length > 0) {
    (src.get('value') as NodePath).replaceWith(
      types.jsxExpressionContainer(buildRequireStatement(types, clone(requireArgs), query)),
    );
  }

  const rawSrc = buildRawSrcAttribute(types, requireArgs, config, query);
  (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer('attributes', rawSrc);
}
Example #2
Source File: svg.ts    From react-optimized-image with MIT License 6 votes vote down vote up
transformSvgComponent = (types: Babel['types'], path: NodePath<JSXElement>): void => {
  // abort if it has already the rawSrc attribute
  if (getAttribute(path, 'rawSrc')) {
    return;
  }

  const src = getAttribute(path, 'src');
  const requireArgs = src ? getRequireArguments(types, src) : undefined;

  if (!src || !requireArgs) {
    return;
  }

  const rawSrc = buildRawSrcAttribute(types, requireArgs);
  (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer('attributes', rawSrc);
  src.remove();
}
Example #3
Source File: visitor.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
doJSXPathName: NodeHandler<JSXOpeningElement['name']> = (name) => {
  const visitors: { [key in ElementTypes]: NodeHandler } = {
    JSXIdentifier: doJSXIdentifierName,
    JSXMemberExpression: doJSXMemberExpressionName,
    JSXNamespacedName: doJSXNamespacedNameName,
  }

  return visitors[name.type](name)
}
Example #4
Source File: visitor.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
doJSXOpeningElement: NodeHandler<
  JSXOpeningElement,
  { relativePath: string }
> = (node, option) => {
  const { stop } = doJSXPathName(node.name)
  if (stop) return { stop }

  const { relativePath } = option
  const line = node.loc?.start.line
  const column = node.loc?.start.column

  const lineAttr: JSXAttribute | null = isNil(line)
    ? null
    : jsxAttribute(
      jsxIdentifier('data-inspector-line'),
      stringLiteral(line.toString()),
    )

  const columnAttr: JSXAttribute | null = isNil(column)
    ? null
    : jsxAttribute(
      jsxIdentifier('data-inspector-column'),
      stringLiteral(column.toString()),
    )

  const relativePathAttr: JSXAttribute = jsxAttribute(
    jsxIdentifier('data-inspector-relative-path'),
    stringLiteral(relativePath),
  )

  const attributes = [lineAttr, columnAttr, relativePathAttr] as JSXAttribute[]

  // Make sure that there are exist together
  if (attributes.every(Boolean)) {
    node.attributes.unshift(...attributes)
  }

  return { result: node }
}
Example #5
Source File: visitor.ts    From react-dev-inspector with MIT License 6 votes vote down vote up
createVisitor = ({ cwd, excludes }: {
  cwd?: string,
  excludes?: (string | RegExp)[],
}): Visitor<PluginPass> => {
  const isExclude = excludes?.length
    ? memo((filePath: string): boolean => pathMatch(filePath, excludes))
    : () => false

  const pathRelative = memo((filePath: string): string => relative(
    cwd ?? process.cwd(),
    filePath,
  ))

  const visitor: Visitor<PluginPass> = {
    JSXOpeningElement: {
      enter(path, state: PluginPass) {
        const filePath = state?.file?.opts?.filename
        if (!filePath) return
        if (isExclude(filePath)) return

        const relativePath = pathRelative(filePath)

        doJSXOpeningElement(
          path.node,
          {
            relativePath,
          },
        )
      },
    },
  }

  return visitor
}
Example #6
Source File: img.ts    From react-optimized-image with MIT License 5 votes vote down vote up
buildConfig = (types: Babel['types'], path: NodePath<JSXElement>): ImageConfig => {
  // build config
  let config: ImageConfig = { ...(globalImageConfig.default || {}) };

  // check if a specific type is set
  const type = getTypeAttribute(path, Object.keys(globalImageConfig.types || {}));

  // add type configs
  if (type && globalImageConfig.types && globalImageConfig.types[type]) {
    config = { ...config, ...globalImageConfig.types[type] };
  }

  // check boolean attributes: webp, inline, url, original
  ['webp', 'inline', 'url', 'original'].forEach((attr) => {
    const value = getBooleanAttribute(path, attr);

    if (typeof value !== 'undefined') {
      (config as Record<string, unknown>)[attr] = value;
    } else if (typeof value === 'undefined' && (config as Record<string, unknown>)[attr] === true) {
      // add attr from global image config
      (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer(
        'attributes',
        types.jsxAttribute(types.jsxIdentifier(attr), null),
      );
    }
  });

  // get sizes
  const sizes = getNumberedArrayAttribute(path, 'sizes');

  if (typeof sizes !== 'undefined') {
    config.sizes = sizes;
  } else if (config.sizes) {
    // add sizes attr from global image config
    (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer(
      'attributes',
      types.jsxAttribute(
        types.jsxIdentifier('sizes'),
        types.jsxExpressionContainer(types.arrayExpression(config.sizes.map((size) => types.numericLiteral(size)))),
      ),
    );
  }

  // get densities
  const densities = getNumberedArrayAttribute(path, 'densities');

  if (typeof densities !== 'undefined') {
    config.densities = densities;
  } else if (config.densities) {
    // add densities attr from global image config
    (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer(
      'attributes',
      types.jsxAttribute(
        types.jsxIdentifier('densities'),
        types.jsxExpressionContainer(types.arrayExpression(config.densities.map((size) => types.numericLiteral(size)))),
      ),
    );
  }

  // get breakpoints
  const breakpoints = getNumberedArrayAttribute(path, 'breakpoints');

  if (typeof breakpoints !== 'undefined') {
    config.breakpoints = breakpoints;
  } else if (config.breakpoints) {
    // add breakpoints attr from global image config
    (path.get('openingElement') as NodePath<JSXOpeningElement>).pushContainer(
      'attributes',
      types.jsxAttribute(
        types.jsxIdentifier('breakpoints'),
        types.jsxExpressionContainer(
          types.arrayExpression(config.breakpoints.map((size) => types.numericLiteral(size))),
        ),
      ),
    );
  }

  return config;
}
Example #7
Source File: inspector-loader.ts    From react-dev-inspector with MIT License 5 votes vote down vote up
/**
 * [webpack compile time]
 *
 * inject line, column, relative-path to JSX html data attribute in source code
 *
 * @type webpack.loader.Loader
 * ref: https://astexplorer.net  +  @babel/parser
 */
export default function inspectorLoader(this: webpack.loader.LoaderContext, source: string) {
  const {
    rootContext: rootPath,
    resourcePath: filePath,
  } = this

  /**
   * example:
   * rootPath: /home/xxx/project
   * filePath: /home/xxx/project/src/ooo/xxx.js
   * relativePath: src/ooo/xxx.js
   */
  const relativePath = path.relative(rootPath, filePath)

  const options: InspectorConfig = getOptions(this)

  const isSkip = pathMatch(filePath, options.excludes)
  if (isSkip) {
    return source
  }

  const ast: Node = parse(source, {
    sourceType: 'module',
    allowUndeclaredExports: true,
    allowImportExportEverywhere: true,
    plugins: [
      'typescript',
      'jsx',
      'decorators-legacy',
      'classProperties',
      ...options?.babelPlugins ?? [],
    ],
    ...options?.babelOptions,
  })


  /**
   * astexplorer + @babel/parser
   * https://astexplorer.net
   */
  traverse(ast, {
    JSXOpeningElement: {
      enter(path) {
        doJSXOpeningElement(
          path.node as JSXOpeningElement,
          { relativePath },
        )
      },
    },
  })

  const {
    code,
  } = generate(ast, {
    decoratorsBeforeExport: true,
  })

  return code
}
Example #8
Source File: jsxConverter.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
private parseJsx(node: Expression): JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement | JSXFragment {
    if (isStringLiteral(node)) {
      return jsxText(node.value);
    }
    if (isCallExpression(node)) {
      const args = node.arguments;

      let name: JSXIdentifier | JSXMemberExpression | undefined;
      if (isIdentifier(args[0]) || isStringLiteral(args[0])) {
        name = jsxIdentifier(isIdentifier(args[0]) ? args[0].name : args[0].value);
      } else if (isMemberExpression(args[0]) && isIdentifier(args[0].object) && isIdentifier(args[0].property)) {
        name = jsxMemberExpression(jsxIdentifier(args[0].object.name), jsxIdentifier(args[0].property.name));
      } else {
        this.debugLog(`fail to parse component ${args[0].type} inside callExpression`);
        return jsxExpressionContainer(node);
      }

      let props: JSXAttribute[] = [];
      if (isObjectExpression(args[1])) {
        props = args[1].properties.map((prop) => {
          if (!isObjectProperty(prop) || !isIdentifier(prop.key)) return null;
          if (isStringLiteral(prop.value)) {
            return jsxAttribute(jsxIdentifier(prop.key.name), prop.value);
          }
          if (isBooleanLiteral(prop.value) && prop.value.value) {
            return jsxAttribute(jsxIdentifier(prop.key.name), null);
          }
          if (isExpression(prop.value)) {
            return jsxAttribute(jsxIdentifier(prop.key.name), jsxExpressionContainer(prop.value));
          }
          return null;
        }).filter((e): e is JSXAttribute => e != null);
      }

      const children = args.slice(2).map((e) => (isExpression(e) ? this.parseJsx(e) : null)).filter((e): e is JSXElement => e != null);

      if (children.length) {
        return jsxElement(jsxOpeningElement(name, props), jsxClosingElement(name), children);
      }

      return jsxElement(jsxOpeningElement(name, props, true), null, []);
    }

    this.debugLog(`fail to parse component ${node.type}`);
    return jsxExpressionContainer(node);
  }
Example #9
Source File: jsxConverter.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
private parseJsx(node: Expression): JSXText | JSXExpressionContainer | JSXSpreadChild | JSXElement | JSXFragment {
    if (isStringLiteral(node)) {
      return jsxText(node.value);
    }
    if (isCallExpression(node)) {
      const args = node.arguments;

      let name: JSXIdentifier | JSXMemberExpression | undefined;
      if (isIdentifier(args[0]) || isStringLiteral(args[0])) {
        name = jsxIdentifier(isIdentifier(args[0]) ? args[0].name : args[0].value);
      } else if (isMemberExpression(args[0]) && isIdentifier(args[0].object) && isIdentifier(args[0].property)) {
        name = jsxMemberExpression(jsxIdentifier(args[0].object.name), jsxIdentifier(args[0].property.name));
      } else {
        this.debugLog(`fail to parse component ${args[0].type} inside callExpression`);
        return jsxExpressionContainer(node);
      }

      let props: JSXAttribute[] = [];
      if (isObjectExpression(args[1])) {
        props = args[1].properties.map((prop) => {
          if (!isObjectProperty(prop) || !isIdentifier(prop.key)) return null;
          if (isStringLiteral(prop.value)) {
            return jsxAttribute(jsxIdentifier(prop.key.name), prop.value);
          }
          if (isBooleanLiteral(prop.value) && prop.value.value) {
            return jsxAttribute(jsxIdentifier(prop.key.name), null);
          }
          if (isExpression(prop.value)) {
            return jsxAttribute(jsxIdentifier(prop.key.name), jsxExpressionContainer(prop.value));
          }
          return null;
        }).filter((e): e is JSXAttribute => e != null);
      }

      const children = args.slice(2).map((e) => (isExpression(e) ? this.parseJsx(e) : null)).filter((e): e is JSXElement => e != null);

      if (children.length) {
        return jsxElement(jsxOpeningElement(name, props), jsxClosingElement(name), children);
      }

      return jsxElement(jsxOpeningElement(name, props, true), null, []);
    }

    this.debugLog(`fail to parse component ${node.type}`);
    return jsxExpressionContainer(node);
  }