尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

templ CLI 完全指南:generate、fmt、lsp、info 命令详解与源码级实践

templ CLI 完全指南:generate、fmt、lsp、info 命令详解与源码级实践 templ CLI 完全指南generate、fmt、lsp、info 命令详解与源码级实践【免费下载链接】templA language for writing HTML user interfaces in Go.项目地址: https://gitcode.com/gh_mirrors/te/templtempl是一个用 Go 编写 HTML 用户界面的模板语言其配套的命令行工具templ是日常开发的核心入口绝大多数用户只需执行templ generate即可把*.templ文件编译为纯 Go 代码。本文以官方 CLI 文档为主线结合仓库源码系统讲解templ的五大命令generate、fmt、lsp、info、version的完整用法、全部参数、CI 集成技巧与实现原理帮助你在本地开发、自动格式化、IDE 集成和持续集成流水线中正确使用它。命令总览templ的命令入口定义在 cmd/templ/main.go直接运行templ不带参数或执行templ help会打印如下用法usage: templ command [args...] templ - build HTML UIs with Go See docs at https://templ.guide commands: generate Generates Go code from templ files fmt Formats templ files lsp Starts a language server for templ files info Displays information about the templ environment version Prints the version从 cmd/templ/main.go 可以看到命令分发的实现generate、fmt、lsp、info各自调用对应子命令包version/--version直接打印templ.Version()定义在 version.go。参数错误时返回退出码64即EX_USAGE命令执行失败返回1。项目main.go还会在收到os.InterruptCtrlC与SIGTERM时优雅取消上下文并输出Stopping...这对长驻进程如 watch 模式很有用。templ generate把 templ 编译为 Go 代码templ generate会遍历当前目录树中所有*.templ文件为每个文件生成对应的_templ.go文件。仓库中所有示例如 examples/hello-world-ssr/hello.templ 与 examples/hello-world-ssr/hello_templ.go就是典型的一一对应产物。完整参数说明usage: templ generate [args...] Generates Go code from templ files. Args: -path path Generates code for all files in path. (default .) -f file Optionally generates code for a single file, e.g. -f header.templ -source-map-visualisations Set to true to generate HTML files to visualise the templ code and its corresponding Go code. -include-version Set to false to skip inclusion of the templ version in the generated code. (default true) -include-timestamp Set to true to include the current time in the generated code. -watch Set to true to watch the path for changes and regenerate code. -cmd cmd Set the command to run after generating code. The command is executed via the system shell ($SHELL on Unix, %COMSPEC% on Windows). -proxy Set the URL to proxy after generating code and executing the command. -proxyport The port the proxy will listen on. (default 7331) -proxybind The address the proxy will listen on. (default 127.0.0.1) -w Number of workers to use when generating code. (default runtime.NumCPUs) -lazy Only generate .go files if the source .templ file is newer. -pprof Port to run the pprof server on. -keep-orphaned-files Keeps orphaned generated templ files. (default false) -v Set log verbosity level to debug. (default info) -log-level Set log verbosity level. (default info, options: debug, info, warn, error) -help Print help and exit.除了上述官方文档列出的参数源码 cmd/templ/generatecmd/main.go 中还定义了一些实用选项实际运行时同样可用参数默认值说明-stdoutfalse配合-f将生成的代码输出到 stdout 而不是写入文件系统仅对单文件有效-checkfalse检查生成文件是否最新而不写盘若有文件需要重新生成则返回非零退出码适合 CI-watch-pattern regexp(.\.go$)|(.\.templ$)监听变化时匹配文件的正则默认监听.go与.templ-ignore-pattern regexp空监听时忽略文件的正则-open-browsertrue设为 false 可阻止使用-proxy时自动打开浏览器-proxy-tls-crt/-proxy-tls-key空提供证书与密钥让代理以 HTTPS 对外服务必须与-proxy同时使用且成对出现-notify-proxyfalse向代理127.0.0.1:7331发送一次 reload 事件地址可用-proxyport/-proxybind调整参数校验逻辑值得注意-watch不能与-f同时使用无法监听单个文件-check不能与-watch、-stdout同时使用-proxy-tls-crt与-proxy-tls-key必须同时提供且只能配合-proxy。如果参数不合法命令会输出完整 usage 文本并以退出码64结束。基础用法示例生成当前目录及其子目录下所有模板的 Go 代码templ generate只生成单个文件官方示例templ generate -f header.templ输出到 stdout适合调试或流水线二次处理templ generate -f header.templ -stdout只生成比源文件更新的.go文件跳过未变化的文件templ generate -lazy开发模式watch、cmd 与 proxy 的协同-watch、-cmd、-proxy三个参数组合起来就是完整的前端开发服务器体验。从 cmd/templ/generatecmd/cmd.go 的实现可以看到完整链路walkAndWatch先递归遍历目录把每个文件事件推入 channelcmd.go随后用 fsnotify 建立递归监听handleEvents按-w指定的 worker 数并发处理事件每个 worker 持有信号量sem : make(chan struct{}, cmd.Args.WorkerCount)控制并发度cmd.gohandlePostGenerationEvents把 100ms 内到达的事件归并debounce判断需要「重启应用」还是「刷新浏览器」Go 代码或 templ 内嵌 Go 代码变化触发重启needsRestarttempl 文本变化触发浏览器 reloadneedsBrowserReloadcmd.go重启命令通过系统 shell 执行Unix 上为$SHELLWindows 上为%COMSPEC%watch 模式下还会注入TEMPL_DEV_MODEtrue与TEMPL_DEV_MODE_WATCH_ROOT环境变量供 runtime/watchmode.go 在运行时判断是否需要热更新页面代理服务器监听-proxybind:-proxyport默认127.0.0.1:7331把请求转发给-proxy指定的应用地址并通过 SSE 向浏览器推送reload消息若-open-browser为 true代理就绪后会自动调用系统浏览器打开页面cmd.go。典型用法templ generate -watch -cmd go run . -proxy http://localhost:8080版本与时间戳注入默认生成的_templ.go文件头部会包含templ版本号-include-version默认 true。从 cmd.go 可见生成器通过generator.WithVersion(templ.Version())和可选的generator.WithTimestamp(time.Now())注入元信息。如果你希望产物完全可复现例如构建缓存友好的场景可分别用-include-versionfalse与-include-timestamptrue/false控制。此外生成前还会执行modcheck.Check校验模块中 templ 版本是否一致不一致只记录警告不会中断生成cmd.go。用 -check 做生成物一致性检查CI 中推荐使用-check它不写盘而是记录所有「需要重新生成但尚未生成」的文件逐个以file is not up to date级别日志输出最终返回错误generated files are not up to date: N file(s) need regeneratingmain.go。这样可以把「忘记提交_templ.go」变成流水线失败而不是运行时才发现代码缺失。templ fmt统一代码风格templ fmt负责格式化模板文件核心实现位于 internal/format/templ.go命令入口在 cmd/templ/fmtcmd/main.go。它支持三种调用方式1. 格式化整个目录templ fmt .会递归处理当前目录及子目录下所有.templ文件并原地写回。2. 从 stdin 读取、向 stdout 输出templ fmt header.templ源码逻辑是当未提供任何文件参数时读取 stdin 全部内容、调用format.Templ格式化后直接写入 stdoutmain.go非常适合嵌入编辑器保存钩子或管道流水线。3. CI 中校验格式templ fmt -fail .-fail模式下只要有文件被改动命令就以退出码1结束templates were not formatted properly从而让格式不合规的提交无法通过 CI。实现上格式化器会统计changesMade若FailIfChange changesMade 0即返回错误main.go。其他实用参数参数默认值说明-stdoutfalse打印到 stdout 而不是原地改写文件-stdin-filepath path空使用-stdout时为格式化器提供文件路径上下文导入整理import organizing必需-w nruntime.NumCPU()格式化 worker 数-prettier-command cmdprettier --stdin-filepath $TEMPL_PRETTIER_FILENAME用于格式化 HTML/CSS/JS 块的命令-prettier-requiredfalse设为 true 时若 prettier 命令不可用则直接返回错误-failfalse有文件被改动则退出码为 1用于 CI需要注意-stdout与-stdin-filepath是 cmd/templ/main.go 中fmt子命令的参数官方文档正文未列全配合-stdout使用可实现对单个文件「格式化但不落盘」templ fmt -stdout -stdin-filepath header.templ header.templprettier 集成机制当PATH中存在prettierd、prettier或npx时templ fmt会调用 prettier 格式化模板中的script与style元素。仓库源码 internal/prettier/prettier.go 揭示了底层机制默认命令按 shell 选择posix 下为prettier --use-tabs --stdin-filepath $TEMPL_PRETTIER_FILENAME也支持 nushell 变体查找顺序是prettier优先、其次prettierdprettier.go实际执行时设置TEMPL_PRETTIER_FILENAME环境变量为当前文件名Unix 通过$SHELL -c、Windows 通过cmd.exe /C运行prettier.go为了保持正确的缩进格式化器会先在内容外层包裹带data-templ-depth属性的div包装层格式化完再借助 internal/htmlfind/htmlfind.go 解析回取真实内容并裁掉包装prettier.go。如果你有自定义 prettier 配置可以通过-prettier-command指定例如prettier --config ./frontend/.prettierrc --use-tabs --stdin-filepath $TEMPL_PRETTIER_FILENAME要求必须存在 prettier 时用-prettier-required。使用 .templignore_fmt 忽略文件若要排除某些文件或目录不参与格式化在被格式化目录的根目录创建.templignore_fmt文件即可。语法为 glob 模式#开头为注释空行忽略# Ignore generated test fixtures. generator/test-*匹配逻辑实现在 internal/ignorefile/ignorefile.go它会对路径的完整路径及每一级目录前缀逐一做filepath.Match因此generator/test-*能同时命中generator/test-foo目录及其下所有文件ignorefile.go。类似地templ generate尊重.templignore_generate文件——从 cmd.go 可见它通过ignorefile.ShouldSkipFunc(cmd.Args.Path, .templignore_generate)加载忽略规则。两个 ignore 文件独立生效分别作用于格式化与生成两个命令。templ lspIDE 集成的语言服务器templ lsp提供 Language Server ProtocolLSP实现供 VSCode 扩展、Neovim 等编辑器集成使用一般不需要用户直接运行。架构templ 与 gopls 的代理桥从 cmd/templ/lspcmd/main.go 可以看到templ 的 LSP 是一个位于「编辑器 ↔ gopls」之间的代理启动时自动寻找并拉起 goplspls.NewGopls建立两个 JSON-RPC 连接编辑器连接 templ servertempl server 再连接 gopls clientproxy.NewServer在中间完成.templ文件到生成 Go 代码的源码映射source map翻译与诊断信息转换相关缓存类位于 cmd/templ/lspcmd/proxy消息通过 lsp/jsonrpc2 包完成编解码。gopls 共享守护进程模式默认情况下templ lsp会启动自己的 gopls 实例。gopls 支持共享 daemon 模式shared daemon mode允许多个客户端连接同一个长驻实例减少资源占用。启用方式templ lsp -gopls-remote-gopls-remote会连接已存在的共享 gopls 实例若不存在则创建一个。完整参数-goplsLog string The file to log gopls output, or leave empty to disable logging. -goplsRPCTrace Set gopls to log input and output messages. -gopls-remote Specify remote gopls instance to connect to. -help Print help and exit. -http string Enable http debug server by setting a listen address (e.g. localhost:7474) -log string The file to log templ LSP output to, or leave empty to disable logging. -pprof Enable pprof web server (default address is localhost:9999)-log与-goplsLog分别把 templ 侧与 gopls 侧的 JSON 日志写入指定文件不指定则静默丢弃-goplsRPCTrace记录双方的完整请求/响应消息-http启动一个 Web 调试面板实现在 cmd/templ/lspcmd/httpdebug-pprof在localhost:9999暴露性能剖析端点。针对大型 monorepo源码还提供-no-preload选项跳过启动时预加载全部 templ 文件改用自定义GOPACKAGESDRIVER实现惰性加载但使用前必须设置好GOPACKAGESDRIVER环境变量main.go。此外-prettier-command与-prettier-required也被 lsp 子命令接受用于编辑器内格式化时集成 prettier。templ info诊断环境信息templ info用于排查环境问题它会并发出四条检查源码 cmd/templ/infocmd/main.goos当前GOOS与GOARCHgogo可执行文件的位置与go version输出找不到时报错gopls通过pls.FindGopls定位 gopls 及其版本templPATH中templ的位置与版本若与当前运行版本不一致会给出version mismatch提示常用于排查「改了代码却跑的是旧版本」的问题prettier在prettier、prettierd中查找可用者及其版本缺失时以 warn 级别提示说明 prettier 集成将不可用。可用参数usage: templ info [args...] Args: -json Output information in JSON format to stdout. (default false) -v Set log verbosity level to debug. (default info) -log-level Set log verbosity level. (default info, options: debug, info, warn, error) -help Print help and exit.需要机器可读输出比如写入诊断报告时使用-json会得到包含os、go、gopls、templ、prettier五部分的缩进 JSON。templ version打印当前templ版本templ version--version是等价别名。结合templ info可以核对「命令行版本」与「项目路径内实际引用的模块版本」是否一致这是遇到诡异生成行为时最常用的第一步诊断。日志与退出码约定所有子命令共享两个日志参数-log-leveldebug/info/warn/error默认info与-v快捷地把级别设为debug。日志经 cmd/templ/sloghandler 输出到 stderr。退出码约定如下定义于 cmd/templ/main.go 与 cmd/templ/generatecmd/main.go退出码含义0成功1命令执行失败如生成错误、fmt -fail发现改动、generate -check发现过期文件64参数解析错误EX_USAGE同时会打印 usage 帮助小结与推荐工作流把上面的知识组合起来可以得到一个生产可用的 templ 工作流日常开发templ generate -watch -cmd go run . -proxy http://localhost:8080保存即自动生成、自动重启、自动刷新浏览器提交前templ fmt .统一格式配合.templignore_fmt与.templignore_generate排除测试夹具等无需处理的目录CI 校验templ fmt -fail .保证格式合规templ generate -check保证生成物已提交环境诊断templ info -json快速定位 go/gopls/templ/prettier 版本问题。这套 CLI 的全部实现都能在当前仓库源码中找到对应位置命令分发在 cmd/templ/main.go生成逻辑在 cmd/templ/generatecmd格式化在 cmd/templ/fmtcmd 与 internal/formatLSP 代理在 cmd/templ/lspcmd环境诊断在 cmd/templ/infocmd忽略规则在 internal/ignorefile。仓库中的 examples 目录则提供了从 hello-world 到 counter、crud、streaming 的完整可运行示例可作为学习 CLI 各模式实际效果的参考素材。【免费下载链接】templA language for writing HTML user interfaces in Go.项目地址: https://gitcode.com/gh_mirrors/te/templ创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表