I am working on a WordPress project using version 6.5, which introduced support for JavaScript modules. I have a parent theme that exports a JavaScript class, and I want to import this class in a child theme. I'm using Webpack for module bundling. However, I'm encountering issues with WebPack saying this module is not found in node_modules
Here's the structure of my project:
Parent Theme (parent-theme/src/js/parent.js
):
// parent.js export class ParentClass { constructor() { console.log('ParentClass initialized'); } }
Child Theme (child-theme/src/js/child.js
):
// child.js import { ParentClass } from 'parent-script'; const instance = new ParentClass();
WordPress Enqueue Script in Child Theme (functions.php
):
function enqueue_child_theme_scripts() { wp_register_script_module( 'parent-script', get_stylesheet_directory_uri() . '/build/js/parent.js', array(), '1.0' ); wp_enqueue_script_module('parent-script'); } add_action('wp_enqueue_scripts', 'enqueue_child_theme_scripts');
Problem:
When I try to build the child theme using Webpack, it throws an error saying that the module parent-script
is not found. How can I properly configure Webpack and WordPress to handle this module import correctly?
Any help or pointers would be greatly appreciated!
Update: WebPack Details
- I have two same configurations for both parent-theme and child-theme.
Configuration:
const path = require('path'); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts'); const wordpressConfig = require('@wordpress/scripts/config/webpack.config'); const styles = { // config related to styles. }; const scripts = { ...wordpressConfig, output: { path: path.resolve(process.cwd(), 'assets', 'build', 'js'), filename: '[name].js', chunkFilename: '[name].js', }, plugins: [ ...wordpressConfig.plugins.map((plugin) => { if (plugin.constructor.name === 'MiniCssExtractPlugin') { plugin.options.filename = '../css/[name].css'; } return plugin; }), new RemoveEmptyScriptsPlugin(), ], optimization: { ...wordpressConfig.optimization, minimizer: [ ...wordpressConfig.optimization.minimizer, new CssMinimizerPlugin(), ], }, entry: { 'handle': path.resolve(process.cwd(), 'src', 'js', 'file-name.js'), }, }; module.exports = [scripts, styles];