Rootree
Github Logo

Bundling With Webpack

Github Logo

Have you gotten bored with writing jQuery and CSS? Then this is the walk-through for you! This will take you all the way from creating an NPM package to having a whole site bundle.

Prerequisite

This tutorial assumes that you:

Steps

  1. In your project folder, run yarn init

  2. Complete the instructions for using our private packages. At the very least you will need to complete step 10.

  3. Run yarn add -D @rootreeweb/rt-webpack-helper

  4. Create a file called webpack.config.js

  5. In that file, add the following boilerplate:

    import path from "path";
    
    import { getWebpackConfig } from "@rootreeweb/rt-webpack-helper";
    
    // You'll probably want to change this to your actual entry point(s).
    // The second argument is whether you want to add a hash to the output file name.
    // This is covered in the notes section below.
    const baseConfig = getWebpackConfig(path.resolve("css", "index.css"), {
    	useHash: false,
    });
    
    export default baseConfig;

    (Adjust entry accordingly, it can also be an array of objects for multiple entries)

  6. Make sure to add the dist directory to your .gitignore file if it isn’t already there.

  7. Adjust package.json to include the following script:

    {
    	"scripts": {
    		"build": "webpack --mode=production"
    	}
    }
  8. Add the outputted script(s) to the page. If you’re using WordPress it will look something like this:

    add_action( 'wp_print_styles', function () {
        wp_enqueue_style( 'my-theme-styles', "/wp-content/themes/my-theme/dist/main.css", array(), '1.0.0' );
    } );
    

Notes

  • The default behaviour is to add the content hashes to the outputted filenames. This is useful for determining if file contents have changed to prevent browser caching issues. This can make importing or enqueueing the generated files more difficult. rt-php-lib provides a function for reading the webpack manifest and determining the correct files to enqueue.
  • @rootreeweb/rt-webpack-helper provides additional configurations. These can be used for CSS-only bundling, or for creating a development environment.
  • There is an assortment of other options for adding or omitting pluigns, creating aliases, or configuring output.