Reflex 自定义组件 CLI 命令实战指南:init、build、share 与发布全流程解析
【免费下载链接】reflex🕸️ Web apps in pure Python 🐍项目地址: https://gitcode.com/GitHub_Trending/re/reflex
Reflex 提供了一组专门的 CLI 子命令(reflex component)用于创建、构建和分享自定义组件(Custom Component)。本指南以官方命令参考文档为主体,结合仓库源码逐条讲解init、build、share及发布流程的完整用法、参数含义与底层实现,读完即可从零搭建一个可发布到 PyPI 的 Reflex 自定义组件包。
reflex component命令组总览
所有自定义组件命令都挂在reflex component子命令下。想查看可用命令列表,运行:
reflex component --help输出如下:
Usage: reflex component [OPTIONS] COMMAND [ARGS]... Subcommands for creating and publishing Custom Components. Options: --help Show this message and exit. Commands: init Initialize a custom component. build Build a custom component. share Collect more details on the published package for gallery.查看某个具体命令的手册,只需在该命令后追加--help,例如reflex component init --help。
从源码层面看,该命令组由 reflex/custom_components/custom_components.py 中的custom_components_cli(一个click.group,见文件第 220 行)实现,并在 reflex/reflex.py 处通过cli.add_command(custom_components_cli, name="component")注册进 Reflex 主 CLI。值得注意的是,源码中除文档列出的init、build、share外,还注册了一个未出现在帮助列表中的install命令(见下文"补充命令"一节)。
reflex component init:初始化自定义组件项目
init用于在当前目录中创建一个完整的自定义组件工程骨架。直接运行:
reflex component init假设你在名为google_auth的文件夹中执行,会看到类似输出:
reflex component init ─────────────────────────────────────── Initializing reflex-google-auth project ─────────────────────────────────────── Info: Populating pyproject.toml with package name: reflex-google-auth Info: Initializing the component directory: custom_components/reflex_google_auth Info: Creating app for testing: google_auth_demo ──────────────────────────────────────────── Initializing google_auth_demo ──────────────────────────────────────────── [07:58:16] Initializing the app directory. console.py:85 Initializing the web directory. console.py:85 Success: Initialized google_auth_demo ─────────────────────────────────── Installing reflex-google-auth in editable mode. ─────────────────────────────────── Info: Package reflex-google-auth installed! Custom component initialized successfully! ─────────────────────────────────────────────────── Project Summary ─────────────────────────────────────────────────── [ README.md ]: Package description. Please add usage examples. [ pyproject.toml ]: Project configuration file. Please fill in details such as your name, email, homepage URL. [ custom_components/ ]: Custom component code template. Start by editing it with your component implementation. [ google_auth_demo/ ]: Demo App. Add more code to this app and test.包名是如何推导出来的
init会利用当前所在文件夹的名称来构造 Python 包名,通常采用 kebab-case(短横线分隔)。例如在google_auth目录下执行,包名就是reflex-google-auth。前缀reflex-有两个作用:降低包名在 PyPI 上发生冲突的概率,同时向社区表明这是一个 Reflex 自定义组件。
源码中的命名推导逻辑位于_get_default_library_name_parts与_validate_library_name(reflex/custom_components/custom_components.py),完整规则如下:
- library name(库名):取当前目录名,剔除所有非字母数字与
-/_的字符并转为小写,再按-或_拆分;若目录名以reflex开头,则自动去掉该前缀;若拆分后没有有效部分(例如目录名本身就是reflex),命令会报错并退出。 - package name(包名):
reflex-{library_name},kebab-case。 - component class name(组件类名):各段首字母大写的 CamelCase,例如
GoogleAuth。 - module name(模块名):各段用下划线连接的 snake_case,例如
google_auth。 - 组件源码目录:
custom_components/reflex_{module_name},例如custom_components/reflex_google_auth。 - 演示应用目录与名称:
{module_name}_demo,例如google_auth_demo。
若自动推导不满足需求,可通过--library-name选项覆盖库名(帮助手册正文中旧称--package-name,当前 CLI 帮助输出与源码均以--library-name为准)。该选项的值必须匹配正则^[a-zA-Z-]+[a-zA-Z0-9-]*$,即只能包含字母、数字与短横线(源码第 395-401 行会校验并拒绝非法输入)。
init的完整参数表
Usage: reflex component init [OPTIONS] Initialize a custom component. Args: library_name: The name of the library. install: Whether to install package from this local custom component in editable mode. loglevel: The log level to use. Raises: Exit: If the pyproject.toml already exists. Options: --library-name TEXT The name of your library. On PyPI, package will be published as `reflex-{library- name}`. --install / --no-install Whether to install package from this local custom component in editable mode. [default: install] --loglevel [debug|info|warning|error|critical] The log level to use. [default: LogLevel.INFO] --help Show this message and exit.| 选项 | 含义 | 默认值 |
|---|---|---|
--library-name TEXT | 指定库名,PyPI 上将以reflex-{library-name}发布 | 由当前目录名自动推导 |
--install / --no-install | 是否以可编辑(editable)模式安装本地包 | install(开启) |
--loglevel [debug\|info\|warning\|error\|critical] | 日志级别 | LogLevel.INFO |
两点易踩的坑(均有源码佐证):
- 若当前目录已经存在
pyproject.toml,init会直接报错中止(源码第 499-501 行),避免覆盖已有工程; - 若
--install开启,命令底层通过python -m pip install -e .完成可编辑安装(_pip_install_on_demand,reflex/custom_components/custom_components.py),之后组件实现的改动会实时反映到使用它的应用中,方便增量开发与测试。
初始化后的目录结构
init执行完毕后会生成以下骨架:
google_auth/ ├── pyproject.toml ├── README.md ├── custom_components/ │ └── reflex_google_auth/ │ ├── google_auth.py │ └── __init__.py └── google_auth_demo/ └── assets/ google_auth_demo/ requirements.txt rxconfig.py各文件/目录的定位如下。
pyproject.toml:包构建与发布的必备配置
pyproject.toml是包能够被构建和发布的前提。init生成的模板(见源码_pyproject_toml_template,reflex/custom_components/custom_components.py)已预填以下信息:
- 包名(如
reflex-google-auth)与版本号0.0.1; - 作者姓名与邮箱(占位为
YOUREMAIL@domain.com,需要手动填写); - 主页 URL(
[project.urls]留空待填); - 许可证默认采用Apache-2.0(与 Reflex 自身一致);
requires-python = ">=3.10";- 依赖
reflex>=当前版本(写入时取仓库constants.Reflex.VERSION); - 可选依赖
dev = ["build", "twine"],供构建与上传使用; - 构建后端为 setuptools,并通过
[tool.setuptools.packages.find]的where = ["custom_components"]指定包源码所在目录; - 分类器
Development Status :: 4 - Beta与关键词reflex、reflex-custom-components。
这些信息如有变化,直接手工编辑该文件即可。
README.md:随包发布的说明文档
README.md由_readme_template(reflex/custom_components/custom_components.py)生成,默认包含安装说明(如pip install reflex-google-auth)与简短描述。通常你会在其中补充用法示例——发布到 PyPI 后,README 会作为包页面的一部分被渲染展示。
custom_components/ 文件夹:组件真实实现
custom_components目录存放的是组件的实际实现代码。这个目录名无需修改——pyproject.toml正是通过它指定 Python 包源码的位置。发布时,包内会包含该目录下的全部内容,而custom_components这层文件夹本身不会被包含。
其中:
reflex_google_auth/__init__.py内容为from .google_auth import *,负责转发导出。包的使用者通过from reflex_google_auth import ABC, XYZ导入组件。reflex_google_auth/google_auth.py预填了代码示例与说明(见源码_source_template,reflex/custom_components/custom_components.py),其核心是一个继承rx.Component的类:
import reflex as rx class GoogleAuth(rx.Component): """GoogleAuth component.""" # 要包装的 React 库(npm 包名)。 library = "Fill-Me" # React 组件标签名。 tag = "Fill-Me" # 如果 tag 是该模块的默认导出,需要设置 is_default = True。 # 当组件导入时没有花括号包裹时,通常需要此设置。 # is_default = True # 如果与项目中其他组件标签重名,可用 alias 避免命名冲突。 # alias = "OtherGoogleAuth" # 组件 props。snake_case 属性名在编译为 JavaScript 时会自动转为 camelCase。 # some_prop: rx.Var[str] = "some default value" # 额外需要安装的依赖库。 # lib_dependencies: list[str] = [] # 事件触发器声明,例如 on_change。 # on_change: rx.EventHandler[lambda e: [e]] google_auth = GoogleAuth.create模板中还提示:部分 React 库与 SSR(服务端渲染)不兼容,此时应改为继承NoSSRComponent而非rx.Component;如需注入自定义 JS 代码,可覆写_get_custom_code。更多包装细节参见 包装 React 组件指南。
演示应用文件夹:测试组件的常规 Reflex App
google_auth_demo是一个常规的 Reflex 应用,源码_demo_app_template(reflex/custom_components/custom_components.py)为其预置了导入语句与组件用法示例。初始化流程会先基于空白模板调用_init创建应用,再覆写主页文件,并把包名追加进requirements.txt(源码第 320-334 行)。进入该目录后,你可以使用任意reflex命令进行测试(如reflex run)。
另外,init还会调用frontend_skeleton.initialize_gitignore生成.gitignore,默认忽略__pycache__/、*.py[cod]、*.egg-info/与dist/(常量定义见 packages/reflex-base/src/reflex_base/constants/custom_components.py)。
reflex component build:生成可分发的构建产物
build命令用于生成.tar.gz与.whl两种分发文件,供上传到目标包索引(如 PyPI)。该命令必须在项目根目录(即pyproject.toml所在目录)执行;构建成功后会生成一个dist文件夹,内含分发文件。
Usage: reflex component build [OPTIONS] Build a custom component. Must be run from the project root directory where the pyproject.toml is. Args: loglevel: The log level to use. Raises: Exit: If the build fails. Options: --loglevel [debug|info|warning|error|critical] The log level to use. [default: LogLevel.INFO] --help Show this message and exit.从源码看,build的底层流程(_run_build,reflex/custom_components/custom_components.py)分两步:
- 调用
_make_pyi_files(),通过PyiGenerator().scan_all(...)为项目内各顶层目录递归生成.pyi类型存根; - 执行
python -m build .(依赖pyproject.toml中声明的 dev 依赖build)。
相关单元测试 tests/units/custom_components/test_custom_components.py 验证了_make_pyi_files会以递归扫描方式、仅针对顶层非隐藏目录(跳过__pycache__)调用scan_all,并且不依赖 Python 3.12 才有的Path.walk,从而保证在 Reflex 支持的 Python 3.10/3.11 上也能正常构建。
发布到包索引:reflex component publish的现状
关于发布命令,官方文档给出了两点重要说明:
- 从 0.7.5 版本起,Reflex 不再代为处理发布流程。要发布到某个包索引,你需要先在该索引(如 PyPI)注册账号,然后手动完成发布:先运行
reflex component build,再使用twine upload、uv publish或你喜欢的其他发布工具上传。 - 文档同时指出:发布前并不强制要求单独运行
build——publish命令在检测到包尚未构建时会自动执行构建。build命令更多是为开发者手动操作提供的便利入口。
发布完成后,可以通过reflex component share将你的构建分享到 Reflex 网站画廊。
reflex component share:向画廊提交组件信息
share用于在包发布后,向 Reflex 官方画廊补充该包的详细信息。其实现是_collect_details_for_gallery(reflex/custom_components/custom_components.py),流程如下:
- 登录鉴权:通过
hosting.authenticated_token()获取访问令牌,未登录则报错退出; - 填写包信息:交互式提示输入已发布的 Python 包名;
- 权限校验与登记:向画廊后端接口发送 POST 请求(携带 Bearer Token),若该包属于其他用户,后端返回 403,命令随即中止;
- 上传预览图:提示输入演示应用的预览图片路径(可跳过,跳过则不上传;文件需存在且可读,文件扩展名会随请求一并提交);
- 填写演示地址:提示输入已部署演示应用的完整 URL(如
https://my-app.reflex.run,可跳过;若填写则必须以http://或https://开头,校验逻辑见_validate_url_with_protocol_prefix,空值允许); - 提交:将参数与图片一并 POST 到画廊后端,整体请求超时上限为 15 秒(常量
POST_CUSTOM_COMPONENTS_GALLERY_TIMEOUT)。
成功提交后终端会提示 "Custom component information successfully shared!"。
补充命令:reflex component install
除了帮助输出中列出的三个命令,源码中还注册了一个install命令(reflex/custom_components/custom_components.py),其作用是以可编辑模式安装当前目录的本地包(等价于python -m pip install -e .),便于在开发过程中随时重新安装本地组件。
从初始化到发布:完整工作流
综合以上命令,一个典型的工作流如下:
- 创建工程目录并进入(如
mkdir google_auth && cd google_auth),运行reflex component init(或指定--library-name)生成骨架,并自动完成可编辑安装; - 编辑
custom_components/reflex_google_auth/google_auth.py实现组件,填写pyproject.toml与README.md中的作者、邮箱、主页与用法示例; - 在
google_auth_demo演示应用中运行reflex run验证组件行为; - 在项目根目录运行
reflex component build,确认dist/下生成.tar.gz与.whl; - 使用
twine upload dist/*或uv publish等工具上传到 PyPI(需先注册账号); - 运行
reflex component share登录并提交画廊信息,向社区分享你的组件。
进一步的背景知识可参考 自定义组件总览 与 发布前置条件。
【免费下载链接】reflex🕸️ Web apps in pure Python 🐍项目地址: https://gitcode.com/GitHub_Trending/re/reflex
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考