Chapters
-
Course Code
Subscribe to download the code!
Subscribe to download the code!
-
This Video
Subscribe to download the video!
Subscribe to download the video!
-
Subtitles
Subscribe to download the subtitles!
Subscribe to download the subtitles!
-
Course Script
Subscribe to download the script!
Subscribe to download the script!
Scroll down to the script below, click on any sentence (including terminal blocks) to jump to that spot in the video!
¡Hola! Bienvenidos a mi laboratorio de frontend, donde vamos a hacer algo que, sinceramente, pensé que nunca volvería a hacer. ¡Algo atrevido! Algo... quizá un poco loco. Vamos a escribir un frontend moderno con cero sistemas de compilación.
Cómo hemos llegado hasta aquí
¡Hora de la historia! hace 7 años hablaba de cómo el JavaScript moderno requiere un sistema de compilación. Gritaba al mundo que teníamos que pasar de crear archivos JavaScript y CSS en un directorio "público" a construirlos con un sistema, como Webpack o Vite.
Estos sistemas de compilación se crearon porque los navegadores no admitían las funciones modernas que queríamos utilizar. Me refiero a la declaración import
, const
, la sintaxis de clases, etc. Si hubieras intentado ejecutar este tipo de JavaScript en un navegador, habrías sido recibido con tristes mensajes de error.
Por tanto, el sistema de compilación transpilaría (que es una palabra elegante para "convertir") ese JavaScript de aspecto nuevo a JavaScript de aspecto antiguo, para que pudiera ejecutarse en el navegador. También combinaría los archivos JavaScript y CSS, para que tuviéramos menos peticiones, podría crear nombres de archivo versionados, procesar TypeScript y JSX, Sass, y mucho más.
Estos sistemas son increíblemente potentes. Pero también añaden complejidad y pueden ralentizar la codificación. Así que estoy aquí, 7 años después, para decir que... ¡puede que ya no necesitemos esos sistemas de compilación! En este tutorial, vamos a escribir todo el JavaScript moderno que conocemos y amamos... pero sin ningún sistema de compilación ni Node. Sólo tú y el navegador: tal y como lo concibieron los Dioses de Internet.
¿Es esto para todos los proyectos?
Ahora, lo admito, hacer esto no será la mejor opción para todos los proyectos. Si quieres usar TypeScript, o estás usando React, Vue o Next.js, probablemente seguirás queriendo un sistema de compilación... y probablemente deberías usar su sistema de compilación. Omitir un sistema de compilación también significa que no hay agitación automática del árbol -si sabes y te importa eso-, aunque aprenderemos cómo puede seguir funcionando.
En su mayor parte, la programación con y sin sistema de compilación es idéntica, pero señalaré las pequeñas diferencias a lo largo del proceso. Y si te estás preguntando por cosas como los preprocesadores Sass o Tailwind, puedes utilizarlos y veremos cómo. El sitio final también va a ser tan eficiente y rápido como uno construido con un sistema de compilación.
Configuración del proyecto
Bien, ¡manos a la obra! Codificar sin un sistema de compilación es una gozada: no necesitas nodos ni pilas. Así que deberías descargarte el código del curso de esta página y codificar conmigo. Después de descomprimir ese archivo, tendrás un directorio start/
con el mismo código que ves aquí. Abre este archivo README.md
. Como de costumbre, contiene todos los detalles de configuración que necesitarás. Yo ya he hecho la mayoría. El último paso es buscar tu terminal, entrar en el proyecto y ejecutar:
symfony serve -d
para utilizar el binario symfony
para iniciar el servidor web incorporado. Mantendré pulsado "comando", haré clic y... ¡hola Vinilo Mixto! Pero vaya que esta cosa tiene un aspecto raro y feo.
Se trata de un proyecto Symfony 6.3 -el mismo proyecto que hemos construido en la serie Symfony-. Tiene Doctrine instalado... pero no tiene nada particularmente especial, y ahora mismo, tiene literalmente cero CSS y JavaScript. No hay ningún directorio assets/
ni nada escondido dentro del directorio public/
.
Lo primero que quiero explorar es la realidad de que nuestro navegador puede manejar más cosas modernas de las que nos imaginamos... ciertamente mucho más de lo que yo me imaginaba hace unos meses. Veamos de qué va todo este revuelo probando nuestro navegador con un JavaScript moderno.
18 Comments
Hey Marius,
Thanks for this tip! Please, correct me if I'm wrong, but I don't see we use Symfony secrets in this course. Is it something that you use internally for your project?
Cheers!
Hey Victor,
It's not being used in the course, but the downloadable code contains a secret called GITHUB_TOKEN
(with the value "CHANGEME" in dev). I guess it's the one from chapter 21 in the "Symfony 6 Fundamentals: Services, Config & Environments" course.
Not a big deal, especially if you go through the courses in order. I just happened to do the courses on different computers and this one didn't have sodium installed yet.
Yea... this is a good tip - for some reason, some PHP installs still don't have Sodium. And, as you said, it's not actually needed. I think we can comment-out its usage to avoid the error entirely.
I just complete this course and I am really glad to say that the AssetMapper is way simpler and more convenient than the encore build system!
This course is must have, a very important topic!
Thank you!
Thanks @Jared and I also agree this is way better than Webpack
Cheers!
Usually I open the 'finish' directory and run composer install (and then yarn install && yarn dev, but of course that's exactly what I'm eager to not do with this tutorial!)
But running the finished project needs more than that, I guess because of tailwind.
Tailwind isn't even in composer.json, so something seems wrong.
I got stuck on something doing the tutorial, so I want to go to the finished project and run it, but now I'm stuck on that.
Since this course is all about not needing a build system, I think you should check in the app.tailwind.css file, so that the 'finish' file works.
Otherwise, you have to build the css file, but then there should be installation instructions in the README. The tailwind bundle downloads the executable, but there appears to be no way to run the bin/console command and get the output file in the right directory. Downloading the tailwind binary works better (since the tutorial has instructions on how to run it).
So after way some playing around, I was able to build the finished project. But please, either add the tailwind css file or the build instructions to the readme of the 'final' folder.
I LOVE AssetMapper. I can't wait to understand it enough to drop the build system.
Hey Tac!
I think you should check in the app.tailwind.css file, so that the 'finish' file works.
Ah, good idea actually :). Btw, now that https://github.com/symfonycasts/tailwind-bundle exists, adding Tailwind is even easier, and you don't need to think about this app.tailwind.css
file anymore.
I LOVE AssetMapper. I can't wait to understand it enough to drop the build system.
It's going to get even better in 6.4! We just merged CSS support, smarter preloading & it looks like downloading vendor files locally (vs using the CDN) will be a first-class citizen. Good stuff coming!
Cheers!
Yes, the tailwind bundle is better.
But there appears to be no '-o' option to write the file:
bin/console tailwind:build -vvv
! [NOTE] Executing Tailwind (pass -v to see more details).
Command:
'/home/tac/g/tacman/asset-mapper/var/tailwind/tailwindcss-linux-x64' '-i' '/home/tac/g/tacman/asset-mapper/assets/styles/app.css' '-o' '/home/tac/g/tacman/asset-mapper/var/tailwind/tailwind.built.css'
So how to do you use the tailwind bundle CLI to run this command?
./bin/tailwindcss -i assets/styles/app.css -o assets/styles/app.tailwind.css
Hey Tac!
No -o
option is needed :). With the tailwind bundle, you run:
bin/console tailwind:build
... and that's it :). Internally, this outputs the built file into the var/tailwind/
directory, but you don't care about this. Further explanation! Assume your source Tailwind file is assets/styles/app.css
:
A) In base.html.twig
, you create a link
tag directly to THIS file: {{ asset('styles/app.css') }}
B) At this point, if TailwindBundle wasn't here to rescue us, then our user would be served the source, uncompiled Tailwind app.css
file, which is not what we want!
C) But, behind the scenes, when AssetMapper fetches assets/styles/app.css
to return to the user, TailwindBundle intercepts that process, grabs the built contents (from the var/tailwind/
directory) and tells AssetMapper to use THOSE.
The end result is that: (1) you create a link
tag directly at the source app.css
file (2) but the user is served the built file and (3) you don't care at all where the actual built file lives - that's handled internally.
Does that make sense? You have to untrain your mind after watching this tutorial - because that bundle makes it so much easier.
Cheers!
I see my problem -- with the bundle, the css file is app.css. In the tutorial, it uses a specific tailwind.css file.
Hello!
And first of all, thank you for you course, once again it's a charm to follow it.
I have a question that I didn't find any help for:
let's say that I come from a good old webpack encore project. Nothing fancy here, I think it's a good candidate for a assetmapper conversion. My app.js is like this:
import './styles/globals.css';
import './styles/table.css';
import './styles/organisms/header.css';
import './styles/molecules/_header_navigation_menu.css';
import './styles/molecules/_header_authentication_menu.css';
import './styles/atoms/_header_link.css';
import './styles/atoms/_header_button.css';
import './styles/molecules/_header_popover.css';
import './styles/organisms/replay_research_form.css';
import './styles/organisms/replay_form.css';
import './styles/molecules/_replay_filters.css';
import './styles/molecules/_replay_searchPreview.css';
import './styles/molecules/_call_to_action.css';
import './styles/organisms/_ranking_table.css';
import './bootstrap.js'; // start the Stimulus application
As we can see, beside stimulus (I will handle its removal with your chapter 12!), it's just a bunch of css files (classic atomic design pattern). But, there is so any css files that I wonder if it's a good idea to add plain html <link tas for each of them? or is there a way to avoid having so many tags? Actually, the compilation is not that bad to allow dev to separate components CSS in a file per each.
What would you do in such a a situation? Stop having 15 .css files? Keep webpack? Put them all with assetmapper? Or do I miss a trick for this usecase?
Thank you in advance! Have a lovely day,
Hey @Nayte91!
I think this is a VERY legitimate question :). Somehow, though it feels totally normal to have 15 import
statements for CSS files, it feels weird to have 15 link
tags for those same 15 CSS files :). But I think we should not feel weird about this: we need to list all 15 CSS files somewhere, there's not really any difference between doing it as import
statements of link
tags :).
However, I think you might be referring more to the possible issue that 15 link tags means 15 requests for those CSS files, vs the 1 that this would compile to in Webpack. With HTTP/2, this is largely not a concern. However, there is certainly SOME upper limit where it is a problem (e.g. imagine you have 1000 CSS files), but I'm not sure where that is. My advice is to put those as 15 links tags and run Lighthouse on it to be sure it's not a problem. You could even - as we do in the last chapter - send a preload header to hint even EARLIER that these file are needed - https://symfonycasts.com/screencast/asset-mapper/preloading#preloading-via-a-header
My guess is that putting 15 link tags is a non-issue, but I get that it feels weird :). Time will tell whether this is something that we al "get used to" or if, perhaps, so many people find it weird for some reason that we add a layer to combine the files. But I'm hoping it doesn't come to that: that's the point of HTTP/2, it removes that need for combining files (so I hope we won't need to re-add it for some reason).
Cheers!
Hi guys:
If I understood correctly in the first video, I would not need Webpack Encore if I use AssetMapper? At least in most of the cases I mean
I am asking just to be sure.
Cesar
yep it is SO, when you are using modern browser, honestly pretty unbelievable, I remember the times of IE6 and now you can just write modern JS and it will work.... awesome thing!
Cheers!
"Houston: no signs of life"
Start the conversation!
What PHP libraries does this tutorial use?
// composer.json
{
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-iconv": "*",
"babdev/pagerfanta-bundle": "^4.0", // v4.2.0
"doctrine/doctrine-bundle": "^2.7", // 2.10.0
"doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.4
"doctrine/orm": "^2.12", // 2.15.2
"knplabs/knp-time-bundle": "^1.18", // v1.20.0
"pagerfanta/doctrine-orm-adapter": "^4.0", // v4.1.0
"pagerfanta/twig": "^4.0", // v4.1.0
"stof/doctrine-extensions-bundle": "^1.7", // v1.7.1
"symfony/asset": "6.3.*", // v6.3.0
"symfony/asset-mapper": "6.3.*", // v6.3.0
"symfony/console": "6.3.*", // v6.3.0
"symfony/dotenv": "6.3.*", // v6.3.0
"symfony/flex": "^2", // v2.3.1
"symfony/framework-bundle": "6.3.*", // v6.3.0
"symfony/http-client": "6.3.*", // v6.3.0
"symfony/monolog-bundle": "^3.0", // v3.8.0
"symfony/proxy-manager-bridge": "6.3.*", // v6.3.0
"symfony/runtime": "6.3.*", // v6.3.0
"symfony/stimulus-bundle": "^2.9", // v2.9.1
"symfony/twig-bundle": "6.3.*", // v6.3.0
"symfony/ux-turbo": "^2.9", // v2.9.1
"symfony/web-link": "6.3.*", // v6.3.0
"symfony/yaml": "6.3.*", // v6.3.0
"twig/extra-bundle": "^2.12|^3.0", // v3.6.1
"twig/twig": "^2.12|^3.0" // v3.6.1
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.4
"symfony/debug-bundle": "6.3.*", // v6.3.0
"symfony/maker-bundle": "^1.41", // v1.49.0
"symfony/stopwatch": "6.3.*", // v6.3.0
"symfony/web-profiler-bundle": "6.3.*", // v6.3.0
"zenstruck/foundry": "^1.21" // v1.33.0
}
}
In case anyone else gets an error about the environment variable GITHUB_TOKEN not being set: It's stored in a secret and Symfony's secrets require the PHP extension "sodium" to be loaded.
Neither
composer check-platform-reqs
norsymfony local:check:requirements
mentions the extension. Maybe add it tocomposer.json
of the course code?