I'm trying to be a good WordPress Citizen π and including my JavaScript the right way, via wp_enqueue_scripts
in my functions.php
.
However doing it this way I don't get hot module reloading (hmr) via webpack-dev-server to work.
Can anybody give me a hint or point me to some documentation?
No reaction here, so I was forced to look for an answer by myself. π Here it is.
What I did not get was how to make the bundle.js
file, which webpack-dev-server makes available just in memory, available to WordPress using wp_enqueue_scripts
in the functions.php
.
my webpack.config.js (extract)
const webpack = require('webpack');
module.exports = {
entry: './src/entry.js',
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
devServer: {
open: true,
hot: true,
publicPath: '/',
proxy: {
'/': {
target: 'http://wordpress:8888/',
changeOrigin: true
}
}
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
The thing is: Although I proxy the dev-sever through my MAMP-server, which runs under http://wordpress:8888
the build.js
file is not made available by webpack-dev-server under http://wordpress:8888/build.js
but under the original url, which is http://localhost:8080/build.js
.
Once I got that a conditional statement in the functions.php
did the trick.
my functions.php (extract)
<?php
// Load my JS
if (!defined('WP_ENVIRONMENT') || WP_ENVIRONMENT == "production") {
function reactTheme_enque_scripts() {
wp_enqueue_script(
'react-theme-js',
get_stylesheet_directory_uri() . '/bundle.js',
[], // dependencies could go here
time(), // version for caching
true // loading it within footer
);
}
} else {
function reactTheme_enque_scripts() {
wp_enqueue_script(
'react-theme-js',
'http://localhost:8080' . '/bundle.js',
[], // dependencies could go here
time(), // version for caching
true // loading it within footer
);
}
}
add_action('wp_enqueue_scripts', 'reactTheme_enque_scripts');
?>
So by now just adding one line within the wp-config.php
I can WordPress make looking for the bundle.js
file, where webpack-dev-server is putting it.
If this line is missing, it loads the bundle.js
file from the root of the theme directory.
my wp-config.php (extract)
define('WP_ENVIRONMENT', 'development');