Bundled JS runing on specific pages

Hi, I’ve just started using Webpack to bundle all my JS into a single file, which executes in every page of my site. However, I realise things are a bit different when using a bundler. For example, if your code contains a selector like document.querySelector(".some-propery") that isn’t in one of the pages, an error is thrown, because a CSS class on one page, might not be on another.

To get around this, I am running a check with window.location.pathname to see if my page is the page the code is meant to run on.

However, this seems like a bit of a hack. I was wondering, is there a better way to make sure the code is only running on pages it’s supposed to run on?

Thanks.