admin管理员组文章数量:1122832
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];
本文标签: theme developmentHow to Use Webpack with WordPress Script Modules and Enqueue a Custom Class
版权声明:本文标题:theme development - How to Use Webpack with WordPress Script Modules and Enqueue a Custom Class 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736300715a1930917.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论