Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine
This tutorial has a new version, check it out!

Hola Webpack Encore

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

Nuestra configuración de CSS y JavaScript está correcta: tenemos el directorio public/ con los archivos app.css y question_show.js. Dentro de nuestros templates - por ejemplo base.html.twig - incluimos los archivos con la etiqueta tradicional link o script. Claro, utilizamos la función {{ asset() }}, pero esta no hace nada importante. Symfony para nada está tocando nuestros archivos del frontend.

Eso está bien. Pero si quieres ponerte serio con el desarrollo de frontend - como utilizar un framework como React o Vue - necesitas llevarlo al siguiente nivel.

Para hacerlo, vamos a utilizar una librería de Node llamada Webpack: la cual es una herramienta estándar en la industria para el manejo de los archivos del frontend. Combina y unifica tus archivos CSS y JavaScript... aunque eso es solo la punta del iceberg de lo que puede hacer.

Pero... para hacer que Webpack funcione en realidad bien necesitas de mucha configuración complicada. Asi que, en el mundo de Symfony, utilizamos una grandiosa librería llamada Webpack Encore. Es una capa ligera por encima de Webpack que... ¡Lo hace más fácil! Y tenemos todo un [tutorial gratuito] (https://symfonycasts.com/screencast/webpack-encore) aquí en SymfonyCasts.

Pero tengamos un curso rápido ahora mismo.

Instalando Webpack Encore

Primero, asegúrate que tienes node instalado:

node -v

Y también yarn:

yarn -v

Tip

Si no tienes Node o Yarn instalado - ve manuales oficiales sobre como instalarlos para tu SO. Para Node, ve https://nodejs.org/en/download/ y para Yarn: https://classic.yarnpkg.com/en/docs/install . Recomendamos utilizar Yarn en la versión 1.x para seguir este tutorial.

Yarn es un gestor de paquetes para Node... básicamente es un Composer para Node.

Antes de que instalemos Encore, asegúrate de guardar todos tus cambios - Yo ya lo hice. Luego corre:

composer require "encore:^1.8"

Espera... hace un minuto dije que Encore es una librería de Node. Entonces, por qué lo estamos instalando con Composer? Excelente pregunta! Este comando en realidad no instala Encore. Nop, instala un diminuto bundle llamado webpack-encore-bundle, el cual ayuda a integrar nuestra app de Symfony con Webpack Encore. Lo mejor de esto es que el bundle contiene una receta muy útil. Mira esto, corre:

git status

Wow! La receta hizo bastante por nosotros! Algo interesante es que modificó nuestro archivo .gitignore. Ábrelo en tu editor.

18 lines .gitignore
... lines 1 - 11
###> symfony/webpack-encore-bundle ###
/node_modules/
/public/build/
npm-debug.log
yarn-error.log
###

Bien! Ahora ignoramos node_modules/ - el cual es la version de Node del directory vendor/ - y algunas otras rutas.

La receta también agregó algunos archivos YAML, los cuales ayudan a configurar algunas cosas - pero en realidad no necesitas verlos.

Lo más importante que hizo la receta fue darnos estos 2 archivos: package.json - el cual es el composer.json de Node - y webpack.config.js, el cual es el archivo de configuración para Webpack Encore.

Revisa el archivo package.json. Esto le dice a Node qué librerías debería descargar y ya tiene las cosas básicas que necesitamos. Aún más importante: @symfony/webpack-encore.

17 lines package.json
{
"devDependencies": {
"@symfony/webpack-encore": "^0.28.2",
"core-js": "^3.0.0",
"regenerator-runtime": "^0.13.2",
"webpack-notifier": "^1.6.0"
},
"license": "UNLICENSED",
"private": true,
"scripts": {
"dev-server": "encore dev-server",
"dev": "encore dev",
"watch": "encore dev --watch",
"build": "encore production --progress"
}
}

Instalando Dependencias de Node con Yarn

Para decirle a Node que instale esas dependencias, corre:

yarn install

Este comando lee package.json y descarga un montón de archivos y directorios dentro de la nueva carpeta node_modules/. Puede tomar algunos minutos en descargar todo y construir un par de paquetes.

Cuando termine, vas a ver dos cosas nuevas. Primero, tienes un nuevo y flamante directorio node_modules/ con demasiadas cosas en él. Y esto ya está siendo ignorado por git. Segundo, creó un archivo yarn.lock, el cual tiene la misma función que composer.lock. Asi que... debes hacer commit del archivo yarn.lock, pero no te preocupes por él.

Ok, Encore está instalado! A continuación, vamos a refactorizar nuestra configuración del fronted para utilizarlo.

Leave a comment!

14
Login or Register to join the conversation
Timera M. Avatar
Timera M. Avatar Timera M. | posted hace 1 año | edited

Hi dears. Can anyone help me with this error. It happens when I launch the command: <blockquote>yarn install</blockquote>.
I tried several ideas, but no way. Please help.
PS C:\Users\Anonymous\Documents\GitHub\Symfony_learnings\codeSymfony> yarn install<br />yarn install v1.22.15<br />info No lockfile found.<br />[1/4] Resolving packages...<br />error An unexpected error occurred: "https:registry.yarnpkg.com/@symfony%2fstimulus-bridge: Invalid URI \"https:registry.yarnpkg.com/@symfony%2fstimulus-bridge\"".<br />info If you think this is a bug, please open a bug report with the information provided in "C:\\Users\\Anonymous\\Documents\\GitHub\\Symfony_learnings\\codeSymfo<br />ny\\yarn-error.log".<br />info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.<br />info There appears to be trouble with your network connection. Retrying...<br />info There appears to be trouble with your network connection. Retrying...<br />info There appears to be trouble with your network connection. Retrying...<br />info There appears to be trouble with your network connection. Retrying...<br />PS C:\Users\Anonymous\Documents\GitHub\Symfony_learnings\codeSymfony>

Reply

Hey Timera M.

Can you try to run it on simple cmd app? not powershel?

Cheers!

Reply
Covi A. Avatar

When i am giving this command yarn --version it's give me this result
user@user-HP-Pavilion-g6-Notebook-PC:~$ yarn --version
0.32+git

and when i am giving this command yarn -v it's giving me this result
user@user-HP-Pavilion-g6-Notebook-PC:~$ yarn -v
ERROR: There are no scenarios; must have at least one.

and when i am trying with this command yarn install then it's give me this result
user@user-HP-Pavilion-g6-Notebook-PC:~/PhpstormProjects/ProjectThree$ yarn install
00h00m00s 0/0: : ERROR: [Errno 2] No such file or directory: 'install'

please remember my os is linux ubuntu

can you help me please

Reply

Hey Covi A.

It seems to me that your Yarn installation is not working correctly, I'd re-install it. Here you can follow the steps of how to do it (I usually do it as shown in the second example) https://phoenixnap.com/kb/h...

Cheers!

Reply
Covi A. Avatar

thank you very much diego for your help. it's working.

1 Reply
Farshad Avatar

I did yarn -v and it showed me the version (meaning that yarn is already isntalled)
so when I did yarn install, it said: succes Already up-to-date
my node_modules directory only has bootstrap in it that I installed manually.
What am I supposed to do?

Reply

Hey Farry7,

If you already have Yarn set up and running, great, that's the first step. Then, you have to install Symfony Encore, and then, run yarn install. If you already did that, try removing your node_modules directory and try again. If nothing works, I'd need to see your package.json file

Cheers!

Reply
Farshad Avatar

It says: yarn add webpack-notifier@^1.6.0 --dev
I tried it and now it says: error An unexpected error occurred "https://registry.yarnpkg.co... Not found"

Reply

Hey @Farry7

I'm glad you got it working! I'm not sure exactly what the problem was with your package.json file, but good debugging!

Cheers!

Reply
Peter-K Avatar

I seems to have lots of warnings when running yarn install

$ yarn install
yarn install v1.22.5
info No lockfile found.
[1/4] Resolving packages...
warning @symfony/webpack-encore > webpack-dev-server > chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
warning @symfony/webpack-encore > webpack-dev-server > chokidar > fsevents@1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
warning @symfony/webpack-encore > webpack > watchpack > watchpack-chokidar2 > chokidar@2.1.8: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
warning @symfony/webpack-encore > resolve-url-loader > rework > css > urix@0.1.0: Please see https://github.com/lydell/u...
warning @symfony/webpack-encore > resolve-url-loader > rework > css > source-map-resolve > urix@0.1.0: Please see https://github.com/lydell/u...
warning @symfony/webpack-encore > resolve-url-loader > rework > css > source-map-resolve > resolve-url@0.2.1: https://github.com/lydell/r...
[2/4] Fetching packages...
warning mini-css-extract-plugin@0.4.2: Invalid bin field for "mini-css-extract-plugin".
info fsevents@1.2.13: The platform "win32" is incompatible with this module.
info "fsevents@1.2.13" is an optional dependency and failed compatibility check. Excluding it from installation.
info fsevents@2.1.3: The platform "win32" is incompatible with this module.
info "fsevents@2.1.3" is an optional dependency and failed compatibility check. Excluding it from installation.
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
Done in 30.85s.

Reply

Hey Peter K.!

As crazy as it sounds, this is completely normal :/. Many of these are due to old dependencies - in the npm world, there are *so* many dependencies, and new major versions are created quickly and before long, your app is relying on abandoned or deprecated packages. So, these are fine - but in a real app, most of them would go away by upgrading to the latest dependencies.

Cheers!

Reply
Oliver-W Avatar
Oliver-W Avatar Oliver-W | posted hace 3 años

A hint where to get node and yarn would be appreciated - thx

Reply

Hey Oliver W.

Hint
NodeJS: https://nodejs.org/en/ - I'd recommend to use LTS version instead of current
Yarn: https://classic.yarnpkg.com... - Here be sure to install classic yarn version, not the new one

BTW thanks for your feedback, we will add a note to the code so nobody get confused in future

Cheers!

Reply
Oliver-W Avatar

@Vladimir Sadicov that was fast - chapeau

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.3.0 || ^8.0.0",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "easycorp/easy-log-handler": "^1.0.7", // v1.0.9
        "sensio/framework-extra-bundle": "^6.0", // v6.2.1
        "symfony/asset": "5.0.*", // v5.0.11
        "symfony/console": "5.0.*", // v5.0.11
        "symfony/debug-bundle": "5.0.*", // v5.0.11
        "symfony/dotenv": "5.0.*", // v5.0.11
        "symfony/flex": "^1.3.1", // v1.17.5
        "symfony/framework-bundle": "5.0.*", // v5.0.11
        "symfony/monolog-bundle": "^3.0", // v3.5.0
        "symfony/profiler-pack": "*", // v1.0.5
        "symfony/routing": "5.1.*", // v5.1.11
        "symfony/twig-pack": "^1.0", // v1.0.1
        "symfony/var-dumper": "5.0.*", // v5.0.11
        "symfony/webpack-encore-bundle": "^1.7", // v1.8.0
        "symfony/yaml": "5.0.*" // v5.0.11
    },
    "require-dev": {
        "symfony/profiler-pack": "^1.0" // v1.0.5
    }
}
userVoice