June 07, 2019
Till this point, we have learnt how to create webpack.config.js and add CSS/JS files to the configuration. Also we have learnt how to render these entries inside our twig templates. Next comes the advanced Webpack configuration before production/deployment.
Webpack Encore provides some prerequired methods such as addRule()
and addLoader()
to add custom loaders to parse specific files included in your project. For example: In my project, I used a file called classifications.yml
which can’t be normally parsed through webpack. So, I had to use a npm package called js-yaml-loader
and added a custom rule as follows:
.addRule({
test: /\.ya?ml$/,
use: 'js-yaml-loader'
})
Before building webpack for production, you need to take care of a few things first
entrypoints.json
createSharedEntry()
to minimise file sizes.This section contains some major issues I faced during my project and how I fixed them through lot of searches.
Problems with webpack commands:
yarn encore dev
to start webpack in the development server. This command compiles every entry you added in your config and the corresponding dependencies to create build inside your public/build/
or web/build/
(#whatever you have specified in your webpack config file).yarn encore dev --watch
to start webpack in dev server with a configuration that watches over your files for changes and recompiles. For VM’s you may need to set up polling options inside webpack.config.js (#only if this command doesn’t work).yarn encore production
to create a production build, for which we may or may need to set up source maps if your website breaks at this command. This may happen if your website did not use Symfony Flex and you hadn’t used twig helpers to render entries. This happens because your production builds are hashed and have different name than your dev builds. So, you may need to link manifest.json in your Symfony project (#only if your website breaks).Sometimes JQuery and Bootstrap plugins don’t work properly. Don’t you worry because this is happening only because we are trying to eliminate all the global variables from our website. JQuery provides a global $ variable
and Boostrap expects this variable to be global so that it can add functions to it. A well defined import includes installing them through yarn and then,
import $ from 'jquery';
import 'bootstrap';
~inside your external js entry file.
If you want to even set up global jQuery variable, use global.jQuery = jQuery
or use autoProvideJQuery()
function inside webpack.config.js
I found these two resources really helpful while my work. I hope they would be of help to you as well.
Thank You, Peace!
Image source: Medium
This blog belongs to Aquib Baig who is a Web Developer and Architect at Zairza. Apart from writing code, I like to play soccer, listen to music and play video games. I am currently working as a summer intern at the umbrella organisation "FOSSi Foundation" under Google Summer Of Code. Follow me on Github