Build apps with Symfony and Webpack

Easily integrate Webpack into your Symfony application with Symfony Encore.

Vahit Saglam
A Young Developer
3 min readJul 23, 2017

--

What is it good for ?

As you know, when you are a fullstack devoloper you have to use many frontend packages in your projects. As the number of packages increases, it becomes more difficult to keep them together.

Symfony Encore is devoloped for make our jobe easier.

Why we should it?

Encore is made by Symfony and works beautifully in Symfony applications.

Encore is a simpler way to integrate Webpack into your application. It wraps Webpack, giving you a clean & powerful API for bundling JavaScript modules, pre-processing CSS & JS and compiling and minifying assets.

Lets install.

First make sure you install Node.js and Yarn package manager.

Then, install Encore into your project with Yarn:

This command creates(or modifies) a package.json file and download dependencies into a node_modulesdirectory.

Now we need to a create webpack.config.js

We need to require @symfony/webpack-encore first.

Imagine you have a simple project with one CSS and one JS, organized into an assets/ directory:

  • assets/js/main.js
  • assets/css/global.scss

Configuring Encore/Webpack

let edit our webpack.config.js

We have specified the path where the compiled files will be stored.

now we need to put our assets fields.

Using Sass

Actually, to use enableSassLoader(), you'll have to install a few more packages. But Encore will tell you exactly what you need.

Using Jquery

Enable Mapping

You can enable source maps so you can debug easily.

Almost done!

we need to export our configuration now.

This is already a rich setup: it outputs 2 files, uses the Sass pre-processor and enables source maps to help debugging.

To build the assets, use the encore executable:

after execute one of these commands now you can add script and link tags into your view.

Examples;

Using Jquery

Lets see how you can use jquery in your project with encore

as you can see all you have to do require jquery.

Using React.js

You want to use ReactJs? Make sure you installed react, along with the babel-preset-react:

Enable react in your webpack.config.js

then you can use Reactjs inside your project.

Now you can see it works!

--

--