DEV Community

vimuth
vimuth

Posted on

Compile assets for wordpress theme

When developing WordPress themes, efficiently managing and compiling assets such as CSS, JavaScript, and images is crucial for performance and maintainability. Utilizing tools like Webpack allows developers to streamline the development process by bundling these assets into optimized packages. This not only improves load times but also enhances the organization of the codebase, making it easier to maintain and update. By integrating modern build tools into WordPress theme development, you can leverage advanced features such as module bundling, pre-processing, and minification, thereby elevating the functionality and efficiency of your themes.

In this tutorial we talk about compiling assets in a very simplified manner.

1. Install and configure WordPress.

You can go to this link and download WordPress.

Create a simple theme

This tutorial says how to activate a simple theme.

2. Start compiling assets.

First let us start by compiling the \assets\js\script.js.

Step 1: Set Up Your Project

To start compiling your JavaScript assets, including the script.js file in your WordPress theme, you'll typically use a tool like Webpack. Webpack will help you bundle your JavaScript files into a single, optimized file that's ready for production use. This can improve load times and performance for your WordPress site.

Here’s a basic guide on how to set up Webpack for your WordPress theme to compile JavaScript assets:

2. Add simple js

Step 1: Set Up Your Project (in theme)

1.Initialize a new Node.js project in your theme directory. Open your terminal, navigate to your theme directory, and run:

   npm init -y
Enter fullscreen mode Exit fullscreen mode

This command creates a package.json file in your theme directory, which will manage your project's dependencies.

2.Install Webpack and its CLI:

   npm install --save-dev webpack webpack-cli
Enter fullscreen mode Exit fullscreen mode

This installs Webpack and the Webpack Command Line Interface, which you'll use to run build processes.

Step 2: Create a Webpack Configuration File

Create a file named webpack.config.js in the root of your theme directory. This file will define how Webpack should handle your JavaScript files. Here’s a simple configuration:

const path = require('path');

module.exports = {
    mode: 'development',  // For production, change this to 'production'
    entry: './assets/js/script.js',  // Entry point for your JavaScript
    output: {
        filename: 'bundle.js',  // Output file
        path: path.resolve(__dirname, 'assets/dist'),  // Directory for output
    }
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Adjust Your script.js (if needed)

If script.js is your main JavaScript file, you might start importing other JS modules or libraries into this file. For example:

console.log('Here is script');
// You can import other scripts or libraries if needed
Enter fullscreen mode Exit fullscreen mode

Step 4: Add Scripts to package.json

Modify the scripts section in your package.json to add a build script:

"scripts": {
    "build": "webpack --config webpack.config.js"
}
Enter fullscreen mode Exit fullscreen mode

This allows you to run npm run build from your terminal to compile your JavaScript using Webpack.

Step 5: Run Webpack

Execute the following command in your terminal:

npm run build
Enter fullscreen mode Exit fullscreen mode

This will compile script.js into bundle.js, which will be placed in assets/dist.

Step 6: Enqueue the Compiled JavaScript in WordPress

Update your functions.php to enqueue the compiled JavaScript file:

function your_theme_enqueue_scripts() {
    wp_enqueue_script('your-theme-script', get_template_directory_uri() . '/assets/dist/bundle.js', array(), false, true);
}
add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

This function loads bundle.js on your WordPress site.

When you come to this point you have compiled your simple js files.

3. Add css

To integrate CSS into your WordPress theme using Webpack, you'll expand on the basic setup for JavaScript compilation by adding support for CSS files. This involves configuring Webpack to handle CSS with appropriate loaders, such as css-loader for processing CSS files and MiniCssExtractPlugin for extracting CSS into separate files instead of bundling it directly into your JavaScript.

Here's how to add CSS handling to your existing Webpack setup:

Step 1: Install Necessary Packages

You'll need to install css-loader to process CSS files and mini-css-extract-plugin to extract the CSS into separate files. Run the following command in your theme directory:

npm install --save-dev css-loader mini-css-extract-plugin
Enter fullscreen mode Exit fullscreen mode

Step 2: Update Your Webpack Configuration

Modify your webpack.config.js to include rules for handling CSS and configure the MiniCssExtractPlugin. Here's an updated configuration:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

module.exports = {
    mode: 'development', // Change to 'production' for production builds
    entry: {
        main: './assets/js/script.js'  // Your main JavaScript entry point
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'assets/dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,  // Extracts CSS into separate files
                    'css-loader'  // Translates CSS into CommonJS modules
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.css'  // Output CSS file name
        })
    ]
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Create or Modify Your CSS File

Create a CSS file or modify an existing one. For example, you can have styles.css in your assets/css folder. Include some basic styles:

/* assets/css/styles.css */
body {
    background-color: #f8f9fa;
    color: #333;
    font-family: Arial, sans-serif;
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Import Your CSS in the JavaScript Entry File

Modify your assets/js/script.js to import the CSS file. This step is necessary for Webpack to recognize and process your CSS file:

import '../css/styles.css';

console.log('Here is script');
Enter fullscreen mode Exit fullscreen mode

Step 5: Build Your Assets

Run the build command to compile your JavaScript and CSS:

npm run build
Enter fullscreen mode Exit fullscreen mode

This command processes both your CSS and JavaScript files, outputting bundle.js and styles.css in the assets/dist folder.

Step 6: Enqueue the Compiled CSS in WordPress

Update your functions.php to enqueue the compiled CSS file alongside the JavaScript:

function your_theme_enqueue_scripts() {
    wp_enqueue_style('your-theme-styles', get_template_directory_uri() . '/assets/dist/styles.css', array(), '1.0.0');
    wp_enqueue_script('your-theme-script', get_template_directory_uri() . '/assets/dist/bundle.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

By following these steps, you can effectively manage both JavaScript and CSS in your WordPress theme using Webpack, ensuring efficient loading and performance optimizations.

4. Install jquery.

To bundle jQuery with Webpack in your WordPress theme, you'll follow these steps to ensure jQuery is included in your JavaScript build process. This approach is helpful when you need a specific version of jQuery or want to bundle your scripts together for reasons such as performance optimizations or particular plugin dependencies.

Step 1: Install jQuery

First, you need to add jQuery to your project using npm, which will allow Webpack to include it in your bundle.

npm install jquery --save
Enter fullscreen mode Exit fullscreen mode

This command installs jQuery and adds it to your package.json, ensuring it's available for Webpack to bundle.

Step 2: Update Your JavaScript Entry File

In your main JavaScript file, which is the entry point for Webpack (typically script.js located in the assets/js directory), import jQuery at the top of the file:

import $ from 'jquery';

$(document).ready(function() {
    console.log('jQuery version:', $.fn.jquery); // Outputs the version of jQuery
    $('body').css('background-color', 'aliceblue');
    console.log('jQuery is ready and changes the background color of the body!');
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Webpack

Adjust your webpack.config.js to ensure it knows how to handle jQuery. Since jQuery is a common dependency, you might also want to provide it as a global variable for any plugins or scripts that expect it to be available globally. You can do this using the ProvidePlugin in Webpack:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack'); // Ensure webpack is required to use the ProvidePlugin

module.exports = {
    mode: 'development', // Change to 'production' when deploying for real users
    entry: './assets/js/script.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'assets/dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.css'
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery' // Make jQuery available as window.jQuery for old plugins
        })
    ]
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build Your Assets

Run the Webpack build to bundle your JavaScript, including jQuery, along with any other assets:

npm run build
Enter fullscreen mode Exit fullscreen mode

This command compiles your JavaScript and CSS into the output files specified in your Webpack configuration (bundle.js and styles.css), located in assets/dist.

Step 5: Enqueue the Compiled Files in WordPress

Update your functions.php file to enqueue the new bundled JavaScript file, which now includes jQuery:

function your_theme_enqueue_scripts() {
    wp_enqueue_style('your-theme-styles', get_template_directory_uri() . '/assets/dist/styles.css');
    wp_enqueue_script('your-theme-script', get_template_directory_uri() . '/assets/dist/bundle.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

By following these steps, jQuery will be bundled with your custom JavaScript, allowing you to leverage its functionality directly in your WordPress theme while using Webpack. This setup is particularly useful for themes that require a specific version of jQuery or need to manage dependencies tightly.

5. Install bootsrap

To integrate Bootstrap into your WordPress theme using Webpack, you'll need to install Bootstrap and configure your Webpack setup to handle both Bootstrap's JavaScript and CSS files. This will involve updating your JavaScript and CSS imports, as well as modifying the Webpack configuration to ensure that all Bootstrap assets are correctly bundled and processed.

Step 1: Install Bootstrap

First, you'll need to add Bootstrap to your project. Since Bootstrap depends on Popper for its dropdowns, tooltips, and popovers, it's typically included automatically when you install Bootstrap via npm:

npm install bootstrap
npm install @popperjs/core --save
Enter fullscreen mode Exit fullscreen mode

Step 2: Import Bootstrap in Your Project

After installing Bootstrap, you need to import both its CSS and JavaScript into your main JavaScript file. This allows Webpack to bundle these resources into your final output.

Update your entry JavaScript file (assets/js/script.js):

import 'bootstrap/dist/css/bootstrap.min.css'; // Import Bootstrap CSS
import 'bootstrap'; // Import Bootstrap JavaScript
import $ from 'jquery';

$(document).ready(function() {
    console.log('jQuery version:', $.fn.jquery); // Outputs the version of jQuery
    console.log('Bootstrap and jQuery are ready!');
    $('.alert').alert(); // Example Bootstrap JS component initialization
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Update Webpack Configuration

You'll need to ensure your Webpack configuration is set up to handle CSS imports, which you likely already have configured. You might also need to adjust handling for font and SVG files, which are used by Bootstrap's icons and other graphical elements.

Update your webpack.config.js to ensure it can handle fonts and SVGs:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');

module.exports = {
    mode: 'development', // Change to 'production' for production builds
    entry: './assets/js/script.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'assets/dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            }
            // If not using images or fonts from Bootstrap or your assets, these rules can be removed
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.css'
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['@popperjs/core', 'default']  // Ensure Popper.js is available
        })
    ]
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build Your Project

After updating your configuration and project files, run your build process:

npm run build
Enter fullscreen mode Exit fullscreen mode

This command compiles your JavaScript and CSS into bundle.js and styles.css, including Bootstrap's resources.

Step 5: Enqueue the Compiled Files in WordPress

Make sure your WordPress theme is set up to load these compiled files:

function your_theme_enqueue_scripts() {
    wp_enqueue_style('your-theme-styles', get_template_directory_uri() . '/assets/dist/styles.css');
    wp_enqueue_script('your-theme-script', get_template_directory_uri() . '/assets/dist/bundle.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

This comprehensive approach integrates Bootstrap into your WordPress theme, allowing you to use both its robust CSS framework and JavaScript components efficiently.

6. Add font awesome.

To integrate Font Awesome into your WordPress theme using Webpack, you will include the Font Awesome library so that you can use its vast array of icons. This setup involves installing Font Awesome, configuring Webpack to handle its assets correctly, and using the icons in your HTML.

Step 1: Install Font Awesome

First, you need to add Font Awesome to your project. You can do this by installing it via npm, which will allow Webpack to bundle its CSS and potentially any font files:

npm install @fortawesome/fontawesome-free
Enter fullscreen mode Exit fullscreen mode

This command installs the free version of Font Awesome, adding it to your package.json and making it available for bundling by Webpack.

Step 2: Import Font Awesome in Your Project

You need to import the Font Awesome CSS into your main JavaScript entry file. This is typically done in the file where you also import other styles or scripts.

Update your main JavaScript entry file (assets/js/script.js):

import '../css/styles.css';

import 'bootstrap/dist/css/bootstrap.min.css'; // Import Bootstrap CSS
import 'bootstrap'; // Import Bootstrap JavaScript
import $ from 'jquery';
import '@fortawesome/fontawesome-free/css/all.min.css';

$(document).ready(function() {
    console.log('jQuery version:', $.fn.jquery); // Outputs the version of jQuery
    console.log('Bootstrap and jQuery are ready!');
    $('.alert').alert(); // Example Bootstrap JS component initialization
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Webpack to Handle Font Files

Font Awesome uses web fonts (eot, svg, ttf, woff, woff2) referenced within its CSS. Your Webpack configuration needs to handle these file types. You can do this by adding a rule for font files in your webpack.config.js:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');

module.exports = {
    mode: 'development', // Switch to 'production' when deploying
    entry: './assets/js/script.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'assets/dist'),
        publicPath: '/wp-content/themes/your-theme/assets/dist/'
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /\.(woff(2)?|eot|ttf|otf|svg)$/,
                type: 'asset/resource',
                generator: {
                    filename: 'fonts/[name][ext][query]' // Configures the folder and file naming
                }
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.css'
        })
    ]
};
Enter fullscreen mode Exit fullscreen mode

Step 4: Build Your Assets

Run your build command to compile the JavaScript, CSS, and font files:

npm run build
Enter fullscreen mode Exit fullscreen mode

This command will process all imports and bundle them into appropriate files in the assets/dist directory.

Step 5: Enqueue the Compiled Files in WordPress

Make sure the compiled CSS that includes Font Awesome styles is enqueued in your WordPress theme:

function your_theme_enqueue_scripts() {
    wp_enqueue_style('your-theme-styles', get_template_directory_uri() . '/assets/dist/styles.css');
    wp_enqueue_script('your-theme-script', get_template_directory_uri() . '/assets/dist/bundle.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'your_theme_enqueue_scripts');
Enter fullscreen mode Exit fullscreen mode

Step 6: Use Font Awesome Icons in Your Theme

Now you can use Font Awesome icons anywhere in your WordPress theme's PHP or HTML files. For example, you can add an icon to your header:

<header>
    <h1>Welcome to My Site <i class="fas fa-smile"></i></h1>
</header>
Enter fullscreen mode Exit fullscreen mode

By following these steps, you will have successfully integrated Font Awesome into your WordPress theme using Webpack, enhancing your site's design with scalable vector icons.

7. Compile images

To compile images that are referenced in your CSS files with Webpack, you'll need to ensure your Webpack configuration can handle image files and properly resolve paths. This involves setting up appropriate loaders to manage these image assets, so they are bundled correctly and their paths updated in the compiled CSS.

Here’s a step-by-step guide on how to set up your Webpack configuration to handle images, especially for use as background images in CSS:

Step 1: Configure Webpack to Handle Image Files

You need to update your webpack.config.js to include a rule for handling image files. This typically involves using the asset/resource module type, which automatically handles emitting files and rewriting the URL in the CSS.

Here’s how you might configure it:

const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require('path');
const webpack = require('webpack');

module.exports = {
    mode: 'development', // Change to 'production' for production builds
    entry: './assets/js/script.js',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'assets/dist'),
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader'
                ]
            },
            {
                test: /\.(woff(2)?|eot|ttf|otf|svg)$/,
                type: 'asset/resource',
                generator: {
                    filename: 'fonts/[name][ext][query]' // Configures the folder and file naming
                }
            },
            {
                test: /\.(png|jpg|jpeg|gif|svg)$/, // Add support for whatever file types you need
                type: 'asset/resource',
                generator: {
                    filename: 'images/[name][ext]' // Output images in an 'images' folder within 'dist'
                }
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: 'styles.css'
        }),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery',
            Popper: ['popper.js', 'default']
        })
    ]
};

Enter fullscreen mode Exit fullscreen mode

Step 2: Reference Images in Your CSS

In your CSS, reference images relative to the CSS file location as you would typically. For example, if your CSS file is in assets/css and your images in assets/images, your CSS might look like this:

body {
    background-image: url('../images/your-image.png'); // Relative path from CSS file to image file
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Build Your Assets

Run your build command:

npm run build
Enter fullscreen mode Exit fullscreen mode

This command compiles your JavaScript and CSS, processes the images, and places them in the specified output directory (assets/dist/images). It also updates the paths in your CSS to point to the new location.

Step 4: Ensure Images are Loading Correctly

  • Check the Output Folder: Verify that the images have been moved to assets/dist/images.
  • Inspect the Compiled CSS: Ensure that the paths to the images in styles.css are correct. They should now reflect the output path set in Webpack's configuration.
  • Load Your Website: Refresh your WordPress site and check that the images are displaying correctly in the browser. Use the developer tools to inspect the network requests if there are any issues.

Top comments (0)