I am trying to reduce the bundle size of th Javascript bundle created by Webpack. So I only want to include specific scripts into the bundle under certain conditions.
E.g. this code should only add login.js
when the user actually is on the login page /login
. On all the other pages, it should not be added:
type Module = {
default: () => void;
}
const resolveModule = (modulePromise: Promise<Module>) => {
modulePromise.then((module: Module) => {
if (typeof module.default === 'function') {
module.default();
}
})
}
document.addEventListener('DOMContentLoaded', () => {
switch(window.location.pathname.split('/')[1]) {
case 'login':
resolveModule(import('./login.js'));
}
});
The problem is, Webpack creates a bundle that includes login.js
all the time. How can I prevent that?