plugin-preact-jsx-signals
v0.2.0
Published
A Babel plugin that automatically wraps JSX expressions and spread attributes containing member access (e.g. `foo.bar`) in `computed(() => ...)` calls from [`@preact/signals`](https://preactjs.com/guide/v10/signals/).
Readme
preact-jsx-signals (Babel plugin)
A Babel plugin that automatically wraps JSX expressions and spread attributes containing member access (e.g. foo.bar) in computed(() => ...) calls from @preact/signals.
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 ./path/to/preact-jsx-signals-plugin.jsUsage with Babel
const { transformSync } = require("@babel/core");
const plugin = require("./preact-jsx-signals-plugin");
const result = transformSync(code, {
filename: "file.tsx",
plugins: [plugin],
parserOpts: { sourceType: "module" },
sourceMaps: true
});Or in your babel.config.js:
module.exports = {
plugins: ["./preact-jsx-signals-plugin"]
};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
