I have created a webpack config that has three entry points which I am trying to split when bundled. Below is my webpack.config.js
var path = require('path');
var webpack = require('webpack');
module.exports = {
mode: "development",
optimization: {
splitChunks: {
chunks: "all"
}
},
context: path.resolve('js'),
entry: {
about: './about_page.js',
home: './home_page.js',
contact: './contact_page.js'
},
output: {
path: path.resolve('build/js/'),
publicPath: '/public/assets/js/',
filename: "[name].js"
},
devServer: {
contentBase: 'public'
},
module: {
rules: [
{
enforce: "pre",
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
options: {
configFile: ".eslint.json"
}
},
{
test: /\.es6$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
extensions: ['.js', '.es6']
},
watch: true
}
I have included the following scripts in my HTML (where home.js
is replaced with the other relevant file names). I am getting an error that shared.js
doesn't exist.
<script src="/public/assets/js/shared.js"></script>
<script src="/public/assets/js/home.js"></script>
When inspecting my page in chrome, I am able to see the individual javascript files and their contents, but none of the code from them is being executed. Each file currently has a console log inside which isn't being logged. but I've tried adding debuggers and writing to the page and still nothing gets hit.
Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel.
Webpack injects some code into main. js which takes care of lazy loading async chunks and stops from loading same chunks again and again. When a route changes, React router calls a Webpack function to load a chunk file and Webpack after done loading runs it, which chunk then would internally ask React to do something.
You assumed that the shared chunk would be called "shared.js" which is wrong.
Amend your config to be:
optimization: {
splitChunks: {
chunks: "all",
name: "shared"
}
},
And now your code will work.
Your issue seems to be with the way you are requiring your built js files in your html.
output: {
path: path.resolve('build/js/'),
publicPath: '/public/assets/js/',
filename: "[name].js"
}
the public path is not for the JS files but rather for static content like images and logos. Your JS files are generated under build/js/
as expected. Update your html to
<script src="./build/js/shared.js"></script>
<script src="./build/js/home.js"></script>
This should work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With