Topics

On this page

Last updated on Oct 21, 2024

Build Tools and Optimizations

Optimizing your workflow begins with configuring build tools that enhance productivity during the development lifecycle. Below are a few tools and techniques essential for any modern WordPress development environment:

Watch Mode

Watch mode allows you to monitor changes in your codebase and automatically rebuild your assets. This is particularly useful for WordPress development, where you need to see changes reflected in real-time.

To configure this in your project, modify your package.json:

"scripts": {
  "start:blocks": "wp-scripts start --config ./node_modules/@wordpress/scripts/config/webpack.config.js --webpack-src-dir=./assets/src/blocks/ --output-path=./assets/build/blocks/",
  "start:js": "wp-scripts start --config ./webpack.config.js",
  "start": "npm-run-all --parallel start:*",
}

Now, running npm start will start the watch mode for your blocks and other assets.

Webpack Configuration for WordPress

When setting up Webpack for WordPress, you need to consider the following:

  1. Entry Points: Define entry points for your scripts and styles. This is where Webpack starts bundling your assets.
  2. Output Paths: Specify the output directory for your bundled assets.
  3. Plugins: Use plugins like MiniCssExtractPlugin to extract CSS into separate files.
  4. Optimization: Minify your assets using plugins like TerserPlugin and css-minimizer-webpack-plugin.
  5. Remove Empty Scripts: Use webpack-remove-empty-scripts to remove empty scripts from your build.
  6. SplitChunks: Configure Webpack’s splitChunks optimization to merge common dependencies into a single file.
  7. Custom Configurations: Extend the default Webpack configuration to include custom setups for CSS extraction and script bundling.
  8. Production Optimization: Ensure your builds are optimized for production by minifying assets, disabling source maps, and concatenating CSS and JS files.

Example Webpack configuration:

/**
 * External dependencies
 */
const fs = require( 'fs' );
const path = require( 'path' );
const CssMinimizerPlugin = require( 'css-minimizer-webpack-plugin' );
const RemoveEmptyScriptsPlugin = require( 'webpack-remove-empty-scripts' );

/**
 * WordPress dependencies
 */
const defaultConfig = require( '@wordpress/scripts/config/webpack.config' );

// Extend the default config.
const sharedConfig = {
	...defaultConfig,
	output: {
		path: path.resolve( process.cwd(), 'assets', 'build', 'js' ),
		filename: '[name].js',
		chunkFilename: '[name].js',
	},
	plugins: [
		...defaultConfig.plugins
			.map(
				( plugin ) => {
					if ( plugin.constructor.name === 'MiniCssExtractPlugin' ) {
						plugin.options.filename = '../css/[name].css';
					}
					return plugin;
				},
			),
		new RemoveEmptyScriptsPlugin(),
	],
	optimization: {
		...defaultConfig.optimization,
		splitChunks: {
			...defaultConfig.optimization.splitChunks,
		},
		minimizer: defaultConfig.optimization.minimizer.concat( [ new CssMinimizerPlugin() ] ),
	},
};

// Generate a webpack config which includes setup for CSS extraction.
// Look for css/scss files and extract them into a build/css directory.
const styles = {
	...sharedConfig,
	entry: () => {
		const entries = {};
		const dir = './assets/src/css';

		if ( ! fs.existsSync( dir ) ) {
			return entries;
		}

		if ( fs.readdirSync( dir ).length === 0 ) {
			return entries;
		}

		fs.readdirSync( dir ).forEach( ( fileName ) => {
			const fullPath = `${ dir }/${ fileName }`;
			if ( ! fs.lstatSync( fullPath ).isDirectory() ) {
				entries[ fileName.replace( /\.[^/.]+$/, '' ) ] = fullPath;
			}
		} );

		return entries;
	},
	module: {
		...sharedConfig.module,
	},
	plugins: [
		...sharedConfig.plugins.filter(
			( plugin ) => plugin.constructor.name !== 'DependencyExtractionWebpackPlugin',
		),
	],

};

const scripts = {
	...sharedConfig,
	entry: {
		'core-navigation': path.resolve( process.cwd(), 'assets', 'src', 'js', 'core-navigation.js' ),
	},
};

module.exports = [
	scripts,
	styles,
];

If you want to setup webpack config for Interactivity API look into How to enable and use the Interactivity API on your projects.

Optimizing Builds for Production

When preparing your WordPress project for production, you need to optimize your build process to ensure faster load times and better performance. Here are some strategies to consider:

  1. Minification: Minify your CSS and JavaScript files to reduce file sizes and improve load times. Use plugins like css-minimizer-webpack-plugin and TerserPlugin to minify your assets.
  2. Source Maps: Disable source maps in production builds to reduce file sizes and improve performance.
  3. Concatenation: Concatenate CSS and JavaScript files to reduce the number of requests made to the server.
  4. Cache Busting: Implement cache-busting techniques to ensure that users always get the latest version of your assets. You can achieve this by appending a version number or hash to your asset URLs.

Contributor

Parth Vaswani

Parth

Parth Vaswani

Software Engineer