Webpack in Wordpress

Webpack is a powerful tool nowadays in front end development, So i decided to use in my project which was using Wordpress and Woo commerce.

Wordpress is not using webpack, I thought it will be good idea to use Webpack but the question was why to use Webpack and what will be the advantages of using it?

The answer was simple for me, just TRY and LEARN something new.

In this process to implement “Webpack”, I defined a set of entry point called “vendor, critical, home, search, product, cart, account and checkout”.

I created multiple entry point, which output the processed file in “dist” folder.

In the “dist” folder, we can see a set of “JS” and “CSS” file for each entry point. So I had a separate “JS” and “CSS” for each pages. So let see, How i maintained to do this?

Lets take “Cart” page and try to understand how i manage to create a separate “JS” and “CSS” file.

Imported “cart.scss” file in the javascript directly and used “sass-loader” and “css-loader” webpack plugin to convert SCSS to CSS file. But the real power of the webpack helped me to extract the CSS from the Javascript. It was “extract-text-webpack-plugin” which extracted the separate CSS file.

With this concept, it was possible to write/split separate JS and CSS file for each pages. But the Wordpress/ Woo commerce come with its own code of JS/CSS and It is very tightly coupled with the PHP. So I decided to remove all the Javascript and CSS from the Wordpress. We can do this in Wordpress by using “wp_dequeue_style” and “wp_dequeue_script” for CSS and Javascript file respectively.

The next question was how to add the specific javascript and CSS file into specific page?

I solved this problem with the use of “assets-webpack-plugin” webpack plugin.

This plug-in outputs a json file with the paths of the generated assets.

finally i used this below Wordpress function, load_style and load_script function. Both the function, gets the “webpack-assets.json” and create link and script tags for specific pages/template.

Calling “load_style()” and “load_script()” in header.php and footer.php, i managed to load the specific CSS and Javascript file.

Hope this will be helpful for those using Wordpress.