In this post I will outline the steps I took to use Webpack to create Javascript modules of custom classes for use in WordPress.
For me this is a second part of creating, implementing and accessing custom Javascript classes for use in WordPress. I started and shared some of the basics in the link below.
The advantage of bundling using Webpack is so you could just reference a single file for multiple from a project. You could include various Javascript files, stylesheets, dependencies and images.
Create Bundle Of Custom Javascript Library With Webpack
Build Webpack Project
Creating and Modifying Necessary Files
We will start off by using NPM to build the initial project structure.
Create a Directory For Project
Open a command prompt and run the following to create a new directory. Choose whatever location you want to store the project at.
mkdir webpack
Then enter that directory.
cd webpack
Use NPM To Create Base Project Structure
Run the following to have NPM create and build the necessary root files.
npm init -y
Install Required Dependencies With NPM
We will need to add the required dependencies for this to build properly. One of the important dependencies is Babel. Babel is a Javascript transpiler used to convert modern ES code that we will use with Webpack to build the module bundle.
npm install webpack webpack-cli @babel/core babel-loader @babel/preset-env --save-dev
Remove CommonJS Type
Next we need to remove a line of code from the package.json file located at the root of the project.
Find the line below and remove it.
"type": "commonjs",
Your final package.json file should look something like this.
{
"name": "webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.27.1",
"@babel/preset-env": "^7.27.2",
"babel-loader": "^10.0.0",
"webpack": "^5.99.9",
"webpack-cli": "^6.0.1"
}
}
Src Directory
Now we need to create a src directory off the root of the project. This is where we will hold our custom Javascript files.
Move your custom Javascript files to this directory. My example I will show is a custom Javascript class I created to build a pie chart. The file name is piechart.js.
Export Custom Javascript CLass
Inside your Javascript custom class, we need to ensure we are exporting the class.
Use the sample below as a syntax guide for how to export.
//my custom class
class MyPieChart { ... }
//add this to export class
export default MyPieChart;Index.JS To Import Custom Class
Inside your src directory along side your custom Javascript file, we need to add a new file. Name the file index.js. This file will need to be used to import your Javascript custom class for use in the build process so the class is globally available.
Below is my sample.
import MyPieChart from './piechart'; // name of Javascript file without extension
window.MyPieChart = MyPieChart;Webpack Configuration File
At the root of the project, we will need to manually create a new file. This file needs to be called webpack.config.js. This is where webpack will look for dependencies and special parameters you specify to build the module.
Below is my sample.
const path = require('path');
module.exports = {
mode: 'production', // or 'development'
entry: './src/index.js', // name of file that imports custom class
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'custom_piechart.js', // any name you desire
library: 'CustomPieChart', // any name for library
libraryTarget: 'umd',
umdNamedDefine: true,
},
module: {
rules:[
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader', // uses babel to address browser compatibility
options: {
presets: ['@babel/preset-env']
}
}
}
]
}
};Build Javascript Module
Finally we are ready to build the module for use in WordPress or other necessary page / site.
Back to the command prompt and enter in the following.
npx webpack
Your newly created Javascript module is now located in the dist folder of this project. Retrieve it and copy to a location of your choice for use.
Continue following below if you need to add to a WordPress block plugin.
Add JS Module To Plugin Directory
To make sure your JS module is available for your plugin, you need to add it to a directory inside the plugin project somewhere. My location I chose was:
<plugin_dir>/assets/scripts/<new_js_module>.js
Add Script For Frontend
At the root of your WordPress block plugin directory, look for the PHP file with the name of your plugin. We need to edit this file. Open it in a text editor and scroll to bottom. We just need to add a WordPress hook to load the script.
r2creations24_my_custom_blocks is the name of my custom block plugin.
r2creations24_my_custom_blocks_script_mypiechart is the name I gave this script for WordPress.
custom_piechart.js is the name of the newly created Javascript module built above.
function r2creations24_my_custom_blocks_enqueue_script()
{
wp_enqueue_script( 'r2creations24_my_custom_blocks_script_mypiechart', plugin_dir_url( __FILE__ ) . 'assets/scripts/custom_piechart.js' );
}
add_action('wp_enqueue_scripts', 'r2creations24_my_custom_blocks_enqueue_script');Access Script On Frontend
I will be showing you how I access the script on the frontend in the render.php file for dynamic rendering. There are no imports needed, that is what the last step above was for. We just need to call the class directly.
var myPieChart = new MyPieChart( ... );Import And Access Script On Backend
The backend is a little different. We will need to import it ourselves then load it like the frontend.
import CustomPieChart from '../../assets/scripts/custom_piechart.js';var myPieChart = new MyPieChart(...);