Desplegar los activos
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login Subscribe¿Cómo introducimos nuestros activos en el sitio? Si "ves la fuente de la página", parece que las cosas funcionan. Vemos el importmap y... aquí abajo, estas rutas parecen correctas: incluso tienen la parte de la versión en sus nombres de archivo.
Compilar activos para producción
Por desgracia, todos estos archivos devuelven un 404. Boo. En el entorno dev, cuando trabajamos localmente, estos archivos no existen físicamente. Pero un oyente interno de Symfony intercepta la petición, encuentra el archivo y los sirve.
Pero en el entorno prod, ese sistema ni siquiera está activo. Es demasiado lento para ejecutarse en producción... así que todo se queda en 404. ¡Y no pasa nada! Hace mucho tiempo, conocimos el comando para solucionar esto:
php bin/console asset-map:compile
El trabajo de este comando es sencillo: coge todos los activos que AssetMapper conoce y los mueve al directorio public/assets/. No es un comando que necesites ejecutar localmente, pero es algo que necesitas ejecutar cuando despliegues.
Copia esto, dirígete a .platform.app.yaml, y baja al paso build. ¡Esto está muy bien! Vamos a dejar que Symfony haga lo suyo en build, y después, añadiremos nuestras propias cosas. Justo aquí, añade php bin/console asset-map:compile. ¡Ya está!
| // ... lines 1 - 43 | |
| hooks: | |
| build: | | |
| // ... lines 46 - 49 | |
| NODE_VERSION=18 symfony-build | |
| php bin/console asset-map:compile | |
| // ... lines 53 - 58 |
¿Por qué ejecutamos esto durante build y no durante deploy? Como regla general, si el trabajo de un comando es "preparar" archivos, debería estar en el paso build. O, otra forma de pensar en ello es: si un comando no requiere una conexión a la base de datos ni a ningún otro servicio en ejecución, hay muchas probabilidades de que sea algo de "construcción".
Tip
Mantén tu paso "desplegar" lo más rápido posible porque las peticiones entrantes se retienen hasta que finaliza. Puedes encontrar más información aquí: https://docs.platform.sh/overview/build-deploy.html#deploy-steps
Vuelve aquí y ejecuta:
git add -p
Ese espacio en blanco me molesta... así que lo arreglaré y preservaré mi cordura. Luego ejecutagit commit -m con un mensaje elegante.
git commit -m "asset-map:compile"
Ya sabes lo que sigue. ¡Pégale un puñetazo!
symfony deploy
Adelantémonos a la parte buena. ¡Ya está aquí! ¡Lo vemos ejecutando el comando!
Compilando activos a
/app/public/assets/Compila 16 activos
También escribe algunos otros archivos dentro del directorio public/assets/:manifest.json y importmap.json. Ayudan a Symfony a volcar el importmap y otras cosas en la página aún más rápido.
Y... ¡listo! Vuelve a girar, actualiza y... ¿¡todavía tiene mal aspecto!? Ah, ¡pero las cosas no están tan mal como crees! Ve a la página principal y abre tu Consola. ¡Ejecuta nuestro JavaScript! ¡Vemos el console.log()!
Construyendo Tailwind en Deploy
Así que JavaScript, ¡comprobado! CSS... no tanto. Seguimos teniendo un 404 enapp.tailwind.css.
Recuerda: cuando veas un 404 a un nombre de archivo que no incluye una parte de versión, como aquí, significa que AssetMapper no puede encontrar ese archivo. ¿Puedes detectar el problema? Este app.tailwind.css es un archivo que estamos construyendo... ¡y no está confirmado en el repositorio! Detendré este comando y lo volveré a ejecutar para que podamos ver los detalles. Sí, estamos construyendo el archivo app.tailwind.css, ignorándolo de Git, y como Platform.sh se despliega utilizando nuestros archivos de Git, ese archivo simplemente falta.
No pasa nada. Esto es sólo otra cosa que tenemos que añadir a nuestro paso build... antes de ejecutar asset-map:compile para que el archivo esté disponible.
Voy a pegar el código correspondiente. Se trata básicamente del mismo código que ejecutamos antes para configurar las cosas localmente, salvo que estamos utilizando la compilación de linux-x64. Lo descargamos, lo movemos al directorio /bin (no importa dónde vaya), lo hacemos ejecutable y ejecutamos el mismo comando para que el archivo de salida esté disponible cuando se ejecuteasset-map:compile.
| // ... lines 1 - 43 | |
| hooks: | |
| build: | | |
| // ... lines 46 - 51 | |
| curl -sLO https://github.com/tailwindlabs/tailwindcss/releases/download/v3.3.2/tailwindcss-linux-x64 | |
| mv tailwindcss-linux-x64 bin/tailwindcss | |
| chmod +x bin/tailwindcss | |
| ./bin/tailwindcss -i assets/styles/app.css -o assets/styles/app.tailwind.css | |
| // ... lines 56 - 63 |
Ah, y no te olvides del TailwindBundle, que facilita un poco el uso de Tailwind, incluido este paso de despliegue.
Volvamos aquí, confirmemos el nuevo cambio de configuración .... y despleguemos de nuevo:
symfony deploy
Incluso mientras se despliega, podemos ver que esto funciona. La última vez había 16 archivos, ahora hay 17. Cuando termine, gira, actualiza y... ¡está vivo! Todas las páginas tienen CSS. ¡Me encanta!
Ahora que estamos en producción, hablemos de las cosas que tenemos que comprobar para asegurarnos de que nuestros activos se sirven rapidísimamente.
11 Comments
Hi,
When I had deployed my project to Platform.sh it's styles didn't work until I changed the line in templates/base.html.twig:
After that all work well.
Did I do something wrong?
My build section in .platform.app.yaml looks like
Hey @Yuri-D
Your issue is you named the final CSS file
app.tailwind.cssthat's why it didn't work until you changed it in your template. You can keep it as is or update your deployment hookCheers!
How can I increase the execution time for the Tailwind build?
Hey Piotr,
It might be so that you need to increase PHP execution time, or what do you mean? You're not enough of default 30 seconds of execution? Could you provide more information on your specific use case, please?
Cheers!
When I run process cloud:deploy and when tailwind compiles, I get this error and the deploy process is interrupted.
Hey Piotr,
I see it now, thanks for sharing more information about it! Yeah, and I also noticed your issue here: https://github.com/SymfonyCasts/tailwind-bundle/issues/48
Seems you have a big project if you hit the timeout of 60s 🙈 But if your Tailwind project isn't that big, that sounds like the process somehow just hangs in the middle :/ I personally haven't hit that problem yet. Do you have some time to debug that case? Any PRs about fixes/improvements are warmly welcome on that repo!
Maybe try to run that specific command manually on your project, from the error message I suppose it should be:
I see you're on the latest v3.4.1 version. I wonder if before it worked for you and now the newest version causes this problem?
And try to stopwatch the time of execution. Does it really last more than 60s? Does it finish without errors?
Cheers!
Hello, I tried to run this command as profiles above, I even used 3 different versions of tailwindcss-linux-x64 but the compilation time was always very similar, around 41 seconds. I don't know why it is so long since my css file is only 80 lines long. Previously it took a fraction of a second.
I started removing some JS libraries and checking them. Well, I got down to 5 seconds, which still seems slow to me, maybe my config file is incorrect and it generates something that is completely unnecessary.
But anyway, everything is within the time limit now.
Thank you for your help.
PS.
But I still think that an optional increase in process execution time would be nice ;).
Hey Piotr,
Glad to hear you were able to make it working with a workaround. Thanks for sharing the solution with others. If more people encountered that problem - yeah, definitely something that would be nice to have out of the box
Cheers!
This not works for me.
I getting this error:
An I'm not sure how I can fix this.
my hooks section looks that:
Even if I will change
php bin/console tailwind:buildto:result it's this same.
Hey @piotrwasilewski!
Right now, using TailwindBundle with the platform.sh Symfony deploy is a bit annoying. It's something we need to improve (I know how, we just need to do it). The problem is that, inside of that
symfony-buildcommand, it runsimportmap:installthenasset-map:compile. But you don't have an opportunity to put thetailwind:buildin the middle of it.To work around this, you can tell the
symfony-buildscript not to do ANYTHING related to AssetMapper. Then run all the commands after on your own.Let me know if this helps!
Cheers!
Yes, that helps.
Thank you.
"Houston: no signs of life"
Start the conversation!