babel-jsx-utils
This library allows you to resolve the actual values of attributes when parsing JSX with Babel. This is useful for things like Babel plugins. It evaluates the value in the local scope, so local variables are ok, but properties passed to the component are not.
For example:
export function Logo() {
const src = "trex.png";
return <img src={src} alt="T-Rex" />;
}
export function Logo({ src }) {
return <img src={src} alt="T-Rex" />;
}
It can handle expressions, but not function calls:
export function Logo() {
const width = 100 * 2;
return <img src={"trex.png"} width={width} alt="T-Rex" />;
}
export function Logo() {
function double(value) {
return value * 2;
}
const width = double(100);
return <img src={"trex.png"} width={width} alt="T-Rex" />;
}
Installation
Install:
yarn install babel-jsx-utils
or
npm install babel-jsx-utils
Usage
import { parse, traverse } from "@babel/core";
const ast = parse(`<Foo bar="hello" />`, {
filename: "foo.js",
presets: ["@babel/preset-react"],
});
traverse(ast, {
JSXOpeningElement(nodePath) {
const values = getAttributeValues(nodePath);
},
});
For more examples, see the tests
API
export declare function getAttributeValues(
nodePath:
| CoreNodePath<JSXOpeningElement>
| TraverseNodePath<JSXOpeningElement>,
onError?: (attributeName: string) => void,
include?: Set<string>
): Record<string, any>;
export declare function getAttributeValue<T = unknown>(
nodePath: CoreNodePath<JSXAttribute> | TraverseNodePath<JSXAttribute>
): {
confident: boolean;
value: T | true;
};