babel-plugin-jsx-expressions
v0.5.0
Published
Plugin to automatically wrap JSX expressions and spread attributes containing any member access with a computed [signal](https://preactjs.com/guide/v10/signals/).
Readme
babel-plugin-jsx-expressions
Plugin to automatically wrap JSX expressions and spread attributes containing any member access with a computed signal.
This enables signal-safe expressions in JSX when using Preact with the Signals library.
Installation
npm install --save-dev @babel/core @preact/signalsAlso install this plugin (locally or from your project):
npm install --save-dev babel-plugin-jsx-expressionsUsage with Babel
const {transformSync} = require("@babel/core");
const plugin = require("babel-plugin-jsx-expressions");
const result = transformSync(code, {
filename: "file.tsx",
plugins: [plugin],
parserOpts: {sourceType: "module"},
sourceMaps: true
});Or in your babel.config.js:
module.exports = {
plugins: ["babel-plugin-jsx-expressions"]
};Usage with esbuild
Install esbuild-babel-plugin to hook Babel into the esbuild
pipeline:
npm install --save-dev esbuild esbuild-babel-pluginThen use it in your build script:
const {build} = require("esbuild");
const esbuildBabelPlugin = require("esbuild-babel-plugin");
const plugin = require("babel-plugin-jsx-expressions");
await build({
entryPoints: ["src/index.tsx"],
bundle: true,
outdir: "dist",
plugins: [
esbuildBabelPlugin({
filter: /\.(jsx?|tsx?)$/,
plugins: [plugin],
}),
],
});Plugin options can be passed alongside the plugin reference:
plugins: [["jsx-expressions", {factories: {svg: {module: "my-svg", name: "svg"}}}]]What it does
This plugin transforms JSX like:
<div>{foo.bar}</div>into:
import {computed} from "@preact/signals";
<div>{computed(() => foo.bar)}</div>It also works for JSX spread attributes:
<Component {...some.obj} />
// becomes
<Component {...computed(() => some.obj)} />Notes
- The plugin ensures the Babel parser supports both
jsxandtypescriptby injecting those parser plugins viamanipulateOptions(). - Only expressions containing a
MemberExpression(e.g.a.b) are wrapped. - Nested JSX containers are handled correctly.
License
MIT
