2

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?

Wordpress Script Modules Ref

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]; 
2
  • 1
    webpack is unaware of parent/child themes, your problem would be the same if your parent theme was a plugin, or if it were a sideproject folder in your computers documents folder. Nothing you do in PHP will influence the webpack build, and you'll need to share the details of what you did with webpack to find the answer
    – Tom J Nowell
    CommentedJul 15, 2024 at 14:57
  • @TomJNowell I have added the WebPack config that I'm usingCommentedJul 16, 2024 at 16:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.