Encore: Setting up your Project

Encore: Setting up your Project

After installing Encore, your app already has one CSS and one JS file, organized into an assets/ directory:

  • assets/js/app.js
  • assets/css/app.css

With Encore, think of your app.js file like a standalone JavaScript application: it will require all of the dependencies it needs (e.g. jQuery or React), including any CSS. Your app.js file is already doing this with a JavaScript import statement:

  1. // assets/js/app.js
  2. // ...
  3. import '../css/app.css';
  4. // var $ = require('jquery');

Encore’s job (via Webpack) is simple: to read and follow all of the require() statements and create one final app.js (and app.css) that contains everything your app needs. Encore can do a lot more: minify files, pre-process Sass/LESS, support React, Vue.js, etc.

Configuring Encore/Webpack

Everything in Encore is configured via a webpack.config.js file at the root of your project. It already holds the basic config you need:

  1. // webpack.config.js
  2. var Encore = require('@symfony/webpack-encore');
  3. Encore
  4. // directory where compiled assets will be stored
  5. .setOutputPath('public/build/')
  6. // public path used by the web server to access the output path
  7. .setPublicPath('/build')
  8. .addEntry('app', './assets/js/app.js')
  9. // ...
  10. ;
  11. // ...

The key part is addEntry(): this tells Encore to load the assets/js/app.js file and follow all of the require() statements. It will then package everything together and - thanks to the first app argument - output final app.js and app.css files into the public/build directory.

To build the assets, run:

  1. # compile assets once
  2. $ yarn encore dev
  3. # if you prefer npm, run:
  4. $ npm run dev
  5. # or, recompile assets automatically when files change
  6. $ yarn encore dev --watch
  7. # if you prefer npm, run:
  8. $ npm run watch
  9. # on deploy, create a production build
  10. $ yarn encore production
  11. # if you prefer npm, run:
  12. $ npm run build

Note

Stop and restart encore each time you update your webpack.config.js file.

Congrats! You now have three new files:

  • public/build/app.js (holds all the JavaScript for your “app” entry)
  • public/build/app.css (holds all the CSS for your “app” entry)
  • public/build/runtime.js (a file that helps Webpack do its job)

Next, include these in your base layout file. Two Twig helpers from WebpackEncoreBundle can do most of the work for you:

  1. {# templates/base.html.twig #}
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <!-- ... -->
  6. {% block stylesheets %}
  7. {# 'app' must match the first argument to addEntry() in webpack.config.js #}
  8. {{ encore_entry_link_tags('app') }}
  9. <!-- Renders a link tag (if your module requires any CSS)
  10. <link rel="stylesheet" href="/build/app.css"> -->
  11. {% endblock %}
  12. {% block javascripts %}
  13. {{ encore_entry_script_tags('app') }}
  14. <!-- Renders app.js & a webpack runtime.js file
  15. <script src="/build/runtime.js" defer></script>
  16. <script src="/build/app.js" defer></script>
  17. See note below about the "defer" attribute -->
  18. {% endblock %}
  19. </head>
  20. <!-- ... -->
  21. </html>

That’s it! When you refresh your page, all of the JavaScript from assets/js/app.js - as well as any other JavaScript files it included - will be executed. All the CSS files that were required will also be displayed.

The encore_entry_link_tags() and encore_entry_script_tags() functions read from an entrypoints.json file that’s generated by Encore to know the exact filename(s) to render. This file is especially useful because you can enable versioning or point assets to a CDN without making any changes to your template: the paths in entrypoints.json will always be the final, correct paths.

If you’re not using Symfony, you can ignore the entrypoints.json file and point to the final, built file directly. entrypoints.json is only required for some optional features.

New in version 1.9.0: The defer attribute on the script tags delays the execution of the JavaScript until the page loads (similar to putting the script at the bottom of the page). The ability to always add this attribute was introduced in WebpackEncoreBundle 1.9.0 and is automatically enabled in that bundle’s recipe in the config/packages/webpack_encore.yaml file. See WebpackEncoreBundle Configuration for more details.

Requiring JavaScript Modules

Webpack is a module bundler, which means that you can require other JavaScript files. First, create a file that exports a function:

  1. // assets/js/greet.js
  2. module.exports = function(name) {
  3. return `Yo yo ${name} - welcome to Encore!`;
  4. };

We’ll use jQuery to print this message on the page. Install it via:

  1. $ yarn add jquery --dev

Great! Use require() to import jquery and greet.js:

  1. // assets/js/app.js
  2. // ...
  3. + // loads the jquery package from node_modules
  4. + var $ = require('jquery');
  5. + // import the function from greet.js (the .js extension is optional)
  6. + // ./ (or ../) means to look for a local file
  7. + var greet = require('./greet');
  8. + $(document).ready(function() {
  9. + $('body').prepend('<h1>'+greet('jill')+'</h1>');
  10. + });

That’s it! If you previously ran encore dev --watch, your final, built files have already been updated: jQuery and greet.js have been automatically added to the output file (app.js). Refresh to see the message!

The import and export Statements

Instead of using require() and module.exports like shown above, JavaScript provides an alternate syntax based on the ECMAScript 6 modules that includes the ability to use dynamic imports.

To export values using the alternate syntax, use export:

  1. // assets/js/greet.js
  2. - module.exports = function(name) {
  3. + export default function(name) {
  4. return `Yo yo ${name} - welcome to Encore!`;
  5. };

To import values, use import:

  1. // assets/js/app.js
  2. - require('../css/app.css');
  3. + import '../css/app.css';
  4. - var $ = require('jquery');
  5. + import $ from 'jquery';
  6. - var greet = require('./greet');
  7. + import greet from './greet';

Page-Specific JavaScript or CSS (Multiple Entries)

So far, you only have one final JavaScript file: app.js. For small applications or SPA’s (Single Page Applications), that might be fine! However, as your app grows, you may want to have page-specific JavaScript or CSS (e.g. checkout, account, etc.). To handle this, create a new “entry” JavaScript file for each page:

  1. // assets/js/checkout.js
  2. // custom code for your checkout page
  1. // assets/js/account.js
  2. // custom code for your account page

Next, use addEntry() to tell Webpack to read these two new files when it builds:

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. .addEntry('app', './assets/js/app.js')
  5. + .addEntry('checkout', './assets/js/checkout.js')
  6. + .addEntry('account', './assets/js/account.js')
  7. // ...

And because you just changed the webpack.config.js file, make sure to stop and restart Encore:

  1. $ yarn run encore dev --watch

Webpack will now output a new checkout.js file and a new account.js file in your build directory. And, if any of those files require/import CSS, Webpack will also output checkout.css and account.css files.

Finally, include the script and link tags on the individual pages where you need them:

  1. {# templates/.../checkout.html.twig #}
  2. {% extends 'base.html.twig' %}
  3. + {% block stylesheets %}
  4. + {{ parent() }}
  5. + {{ encore_entry_link_tags('checkout') }}
  6. + {% endblock %}
  7. + {% block javascripts %}
  8. + {{ parent() }}
  9. + {{ encore_entry_script_tags('checkout') }}
  10. + {% endblock %}

Now, the checkout page will contain all the JavaScript and CSS for the app entry (because this is included in base.html.twig and there is the {{ parent() }} call) and your checkout entry.

See Creating Page-Specific CSS/JS for more details. To avoid duplicating the same code in different entry files, see Preventing Duplication by “Splitting” Shared Code into Separate Files.

Using Sass/LESS/Stylus

You’ve already mastered the basics of Encore. Nice! But, there are many more features that you can opt into if you need them. For example, instead of using plain CSS you can also use Sass, LESS or Stylus. To use Sass, rename the app.css file to app.scss and update the import statement:

  1. // assets/js/app.js
  2. - import '../css/app.css';
  3. + import '../css/app.scss';

Then, tell Encore to enable the Sass pre-processor:

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. + .enableSassLoader()
  5. ;

Because you just changed your webpack.config.js file, you’ll need to restart Encore. When you do, you’ll see an error!

  1. > Error: Install sass-loader & sass to use enableSassLoader()
  2. > yarn add [email protected]^10.0.0 sass --dev

Encore supports many features. But, instead of forcing all of them on you, when you need a feature, Encore will tell you what you need to install. Run:

  1. $ yarn add [email protected]^10.0.0 sass --dev
  2. $ yarn encore dev --watch

Your app now supports Sass. Encore also supports LESS and Stylus. See CSS Preprocessors: Sass, LESS, Stylus, etc..

Compiling Only a CSS File

Caution

Using addStyleEntry() is supported, but not recommended. A better option is to follow the pattern above: use addEntry() to point to a JavaScript file, then require the CSS needed from inside of that.

If you want to only compile a CSS file, that’s possible via addStyleEntry():

  1. // webpack.config.js
  2. Encore
  3. // ...
  4. .addStyleEntry('some_page', './assets/css/some_page.css')
  5. ;

This will output a new some_page.css.

Keep Going!

Encore supports many more features! For a full list of what you can do, see Encore’s index.js file. Or, go back to list of Encore articles.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.