Closed joerdav closed 2 weeks ago
I've had a crack at a version that uses the Go AST parser to do the replacement and rewrite https://github.com/a-h/imports
WDYT? Anything useful in there?
There is a lot useful in here I think. I see that you call updateImports
multiple times, I wondered why you don't run it on the generated go code rather than segments of the template?
From my first read am I right in assuming this wouldn't yet remove unused imports or sort them in the style that gopls does?
Apart from that looks good to me, though I don't think there is anything of use in this PR if we go down this route, so we're better off starting fresh.
Yeah, I only thought about doing it on the generated code after I'd written it all. 😂 It would be much simpler, I think.
For removing unused imports and sorting them, it would be possible to do that if the organise imports functionality ran updateImports
on the generated file, parsed the results, and moved the entire set of import statements from the generated *_templ.go
file to the first Go code node in the *.templ
file (or created it, if one doesn't exist, like the example does).
However, doing that would mean that io
and bytes
etc. would appear in the templ file which would be jarring to users. But... if we took your idea of only referencing a specific templ package (e.g. runtime github.com/a-h/templ/runtime/v2
in the generated code, then you'd only see that one package in the templ file, which I think would be a great design overall.
In my defence, it was late. 😁
This PR currently contains the following changes, which we may or may not want, yet to be decided:
Remove default dependency on
io
,bytes
,strings
,context
from generated templates, so onlygithub.com/a-h/templ
is required. Ifgithub.com/a-h/templ
is imported in a.templ
file, don’t write it twice. Ifgithub.com/a-h/templ
is not imported in a.templ
, write it to the generated file (for backwards compatibility), but warn that it is a problem, tell the user they should runtempl fmt
. Updatetempl fmt
to addgithub.com/a-h/templ
as a dep to any templates that don’t have it. Trick gopls into supporting code actions for our generated files.