JSX Middlewares
JSX Middlewares allows you to change the behavior of JSX renderer by adding middlewares. This allows you to enhance JSX with additional features that were not possible before, such as adding support for custom attributes and Angular-like directives.
Installation
- npm
- Yarn
- pnpm
npm install jsx-middlewares
yarn add jsx-middlewares
pnpm add jsx-middlewares
Setup your JSX transpiler
To use JSX Middlewares, you need to setup your JSX transpiler to use the jsx-middlewares/react
package as the JSX factory. This is done differently depending on the transpiler you are using.
- Typescript
- Babel
- Vite
- Vite SWC
- Webpack
- Per file
{
"compilerOptions": {
"jsxImportSource": "jsx-middlewares/react"
}
}
{
"plugins": [
[
"@babel/plugin-transform-react-jsx",
{
"importSource": "jsx-middlewares/react"
}
]
]
}
If you are using Typescript, you can use the Typescript configuration too.
import { defineConfig } from 'vite';
export default defineConfig({
esbuild: {
jsxImportSource: 'jsx-middlewares/react',
},
});
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
export default defineConfig({
plugins: [
react({
jsxImportSource: 'jsx-middlewares/react',
}),
],
});
module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
use: [
{
loader: 'babel-loader',
options: {
plugins: [
[
'@babel/plugin-transform-react-jsx',
{
importSource: 'jsx-middlewares/react',
},
],
],
},
},
],
},
],
},
};
Most JSX transpilers allow you to specify the JSX factory per file. This is useful if you want to use JSX Middlewares in only some files.
/** @jsxImportSource jsx-middlewares/react */
export function App() {
return <h1>Hello World</h1>;
}
Usage
Firstly, you need to add middlewares at the start of your application.
import { addMiddlewares } from 'jsx-middlewares/react';
addMiddlewares(function emojiMiddleware(next, type, props, key) {
// Modify the props to add an emoji to the text
if (typeof type === 'string' && typeof props.children === 'string') {
props = {
...props,
children: props.children + ' 🎉',
};
}
// Call the next middleware with the new props
// If there is no next middleware, it will call the original JSX renderer
return next(type, props, key);
});
Then, you can write your JSX as usual.
export function App() {
return (
<div>
<h1>Hello World</h1>
<p>This is a paragraph</p>
</div>
);
}
The output will be like this:
Hello World 🎉
This is a paragraph 🎉
What's next?
For more examples of what you can do with JSX Middlewares, check out the examples section.