@thinke/babel-plugin-solidjs-on-react
v0.1.6
Published
让 SolidJS 和 React 共存
Readme
@thinke/babel-plugin-solidjs-on-react
自动为 SolidJS 组件添加 withSolid 工厂函数包装的 Babel 插件。
🚀 功能特性
- 🔧 自动转换:自动检测并转换包含 JSX 的组件函数
- 🎯 智能识别:支持多种组件定义方式的自动识别
- ⚡ 零配置:开箱即用,无需额外配置
- 🛠️ 可定制:支持自定义
withSolid函数名和导入路径 - 🔍 防重复:智能检测已包装的组件,避免重复转换
- 📦 自动导入:自动添加
withSolid导入语句
📦 安装
npm install --save-dev @thinke/babel-plugin-solidjs-on-react
# 或
yarn add --dev @thinke/babel-plugin-solidjs-on-react
# 或
pnpm add --dev @thinke/babel-plugin-solidjs-on-react🛠️ 配置
基础配置
在你的 Babel 配置文件(.babelrc 或 babel.config.js)中添加插件:
module.exports = {
presets: ['@babel/preset-env'],
plugins: ['@thinke/babel-plugin-solidjs-on-react']
}高级配置
module.exports = {
presets: ['@babel/preset-env'],
plugins: [
[
'@thinke/babel-plugin-solidjs-on-react',
{
// 自定义 withSolid 函数名
withSolidFunctionName: 'MyWithSolid',
// 自定义导入路径
withSolidImportPath: '@my-custom-path/MyWithSolid'
}
]
]
}配置选项
| 选项 | 类型 | 默认值 | 描述 |
| ----------------------- | -------- | -------------------------------------- | ---------------------- |
| withSolidFunctionName | string | "withSolid" | 指定包装函数的名称 |
| withSolidImportPath | string | "@thinke/solidjs-on-react/withSolid" | 指定包装函数的导入路径 |
支持 函数体内的指令
包装
export const Component2 = () => {
'with solid'
return (
<div>
<h1 class="hello">hello world</h1>
</div>
)
}不包装
export const Component2 = () => {
'not with solid'
return (
<div>
<h1 class="hello">hello world</h1>
</div>
)
}🎯 支持的组件类型
插件支持以下组件定义形式的自动转换:
1. 箭头函数组件
// 转换前
export const Component1 = () => {
return (
<div>
<h1 class="hello">hello world</h1>
</div>
);
};
// 转换后
import { withSolid } from "@thinke/solidjs-on-react/withSolid";
export const Component1 = withSolid(() => {
return (
<div>
<h1 class="hello">hello world</h1>
</div>
);
});2. 函数声明组件
// 转换前
export function Component2() {
return (
<div>
<h1 class="hello">hello world</h1>
</div>
);
}
// 转换后
import { withSolid } from "@thinke/solidjs-on-react/withSolid";
export const Component2 = withSolid(() => {
return (
<div>
<h1 class="hello">hello world</h1>
</div>
);
});🔍 转换规则
自动检测条件
插件会自动检测满足以下条件的组件:
- 返回 JSX:函数体或箭头函数直接返回 JSX 元素或 JSX 片段
- 函数类型:支持以下函数类型:
- 箭头函数表达式 (
() => {}) - 函数声明 (
function Component() {})
- 箭头函数表达式 (
智能忽略
插件会智能跳过以下情况:
- 已经被
withSolid包装的组件 - 不返回 JSX 的函数
- 非函数类型的节点
自动导入
当检测到需要包装的组件时,插件会:
- 检查文件是否已导入
withSolid函数 - 如果未导入,自动在文件顶部添加导入语句
- 导入语句会插入到其他导入语句之后,代码之前
⚠️ 注意事项
- 组件必须有返回值:组件必须返回 JSX 才会被转换
- 函数声明转换:函数声明会被转换为变量声明
- 导入冲突:请确保
withSolid函数名不与现有导入冲突 - TypeScript 支持:插件完全支持 TypeScript 文件
🤝 贡献
欢迎提交 Issue 和 Pull Request 来改进这个插件!
📄 许可证
MIT License
