Utilities for working with Babel and JSX
npm install babel-jsx-utilsThis 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:
``jsx
// OK
export function Logo() {
const src = "trex.png";
return ;
}
`
`jsx`
// Not OK
export function Logo({ src }) {
return ;
}
It can handle expressions, but not function calls:
`jsx
// OK
export function Logo() {
const width = 100 * 2;
return
;
}
`
`jsx
// Not OK
export function Logo() {
function double(value) {
return value * 2;
}
const width = double(100);
return
;
}
`
Install:
`shell`
yarn install babel-jsx-utils
or
`shell`
npm install babel-jsx-utils
`js
import { parse, traverse } from "@babel/core";
const ast = parse(, {
filename: "foo.js",
presets: ["@babel/preset-react"],
});
traverse(ast, {
JSXOpeningElement(nodePath) {
const values = getAttributeValues(nodePath);
// values = { bar: "Hello" }
},
});
`
For more examples, see the tests
`typescriptonError
/**
* Get all attribute values of a JSX element. This only includes values that can be
* statically-analysed. Pass the callback to be notified if an attribute cannot be resolved.confident
*
* @param nodePath The NodePath of the JSX opening element
* @param onError Called with the attribute name if it is present but cannot be resolved
* @param include If present, only these props are evaluated. Does not apply to spread attributes.
*/
export declare function getAttributeValues(
nodePath:
| CoreNodePath
| TraverseNodePath
onError?: (attributeName: string) => void,
include?: Set
): Record
/**
* Attempt to get the value of a JSX attribute. Returns an object with the
* properties , which is false if the value cannot be resolvedvalue
* in the current scope, and which is the value if it can be.true
*
* If the attribute is empty, then the returned value is , e.g.
* would return true for the eager attribute.``
*
* @param nodePath The NodePath of the JSXAttribute
*/
export declare function getAttributeValue
nodePath: CoreNodePath
): {
confident: boolean;
value: T | true;
};