I have some on page script that produces a constant ReferenceError: $ is not defined
error.
The jQuery is loaded at the bottom of the html page just before the tag. I have added a DOM listener so the code can wait for the JQuery load. Can you see anything wrong, code is bellow.
Webpack config:
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
console.log 1 works, console.log 2 doesn't
{literal}
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function(event) {
console.log('DOM loaded and parsed 1'); // Works!
if ($('.add-user').length) {
const addUser = (callbackFunction) => {
const data = {
signup_name: $('#signup-name').val(),
user_name: $('#user-name').val(),
};
console.log(data);
callbackFunction();
return data;
}
}
console.log('DOM fully loaded and parsed 2'); // Doesn't Work?
});
</script>
{/literal}
So it seems that jQuery is not available due to Webpack settings.
After some research i found an answer that helped solve the error:
https://stackoverflow.com/a/46937798/10814553
Install expose-loader: npm install expose-loader --save-dev
and add this to webpack.config.js
module: {
rules: [
{
// Exposes jQuery for use outside Webpack build
test: require.resolve('jquery'),
use: [{
loader: 'expose-loader',
options: 'jQuery'
},{
loader: 'expose-loader',
options: '$'
}]
}
]
}
and make sure you also added the plugin
plugins: [
// Provides jQuery for other JS bundled with Webpack
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]