How to load a separate JS file in Shopware 6 using webpack?
I'm trying to load a separate javascript file next to the all.js file by using WebPack.
The all.js file can get really big and you're loading unnecessary javascript on a page. So by using code splitting (which should be possible since WebPack is implemented in Shopware 6) and dynamic imports you could stop loading unnecessary javascript.
I've added a webpack.config.js file inside the root of my theme plugin like so:
module.exports = {
entry: {
main: './src/main.js',
separateFile: './src/js/separate.js'
},
output: {
filename: '[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
};
After running bin/build-storefront.sh
there is no separate JS file added in the public folder.
I'm also trying to dynamically load this JS file in src/Resources/app/storefront/src/main.js but this results in a 404 since the separate file doesn't exist.
If someone lands on this post and wants to know more about this topic: Async JavaScript and get rid of the all.js in the Storefront
This will not work since all pre-compiled assets of plugins are collected in the ThemeCompiler
and concatenated into one single script. This is done in PHP since node is not a requirement for production environments.
You could try to add separate scripts as additional custom assets, but you would still have to extend the template to add the corresponding script
tags manually.