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:
- Have a working Node.js environment
- Have Yarn 4 or later installed
Steps
-
In your project folder, run
yarn init -
Complete the instructions for using our private packages. At the very least you will need to complete step 10.
-
Run
yarn add -D @rootreeweb/rt-webpack-helper -
Create a file called
webpack.config.js -
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)
-
Make sure to add the
distdirectory to your.gitignorefile if it isn’t already there. -
Adjust package.json to include the following script:
{ "scripts": { "build": "webpack --mode=production" } } -
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-helperprovides 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.