jsx-to-xml v0.0.0
jsx-to-xml
Tiny package to stringify a JSX tree into XML/HTML. 0.6kB and no dependencies.
Example
const feedTitle = 'My RSS Feed';
const Item = ({ name }) => <>Hi {name}</>;
const xml = (
<rss version={2}>
<title>{feedTitle}</title>
<Item name="bob" />
</rss>
);
console.log(xml);
// prints: '<rss version="2"><title>My RSS Feed</title>Hi bob</rss>'Install
npm install -S jsx-to-xmlSetup
If you want to use this library to transform every .jsx/.tsx file in your repository, then you can add the following to your tsconfig.json file:
{
"compilerOptions": {
+ "jsx": "react-jsx",
}
}Alternatively, you can apply this library to specific .jsx/.tsx files only, by adding the following comment to the top of the file:
+ /* @jsxImportSource jsx-to-xml */Special Cases
- You can use JSX fragments, they will not appear in the output
- You can import
Commentand use<Comment>…</Comment>, which will get converted into<!--…--> - You can import
CDataand use<CData>…</CData>, which will get converted into<![CDATA[…]]>
Type Safety
To create TypeScript definitons for every component that you use, create a new file (for example global.def.ts), and include the following content:
/** @internal */
declare global {
namespace JSX {
interface IntrinsicElements {
// list your components and their propsx here:
example: { a?: string; b?: number; c?: boolean };
rect: { width: number; height: number };
}
}
}
export {};The example above defines two components: <example /> and <rect />, with a mix of optional and required props.
If you're creating a library, you should normally include /** @internal */ above the declare global { … } block, and enable stripInternal in tsconfig.json, so that these global types are not available to anyone consuming your library.
1 year ago