Using a module bundler to optimize JavaScript
We can optimize our usage of JavaScript files when using a module bundler. Instead of importing all the Bootstrap 5 JavaScript source files like we just did before, we can import only the ones we need.
In the source code of Bootstrap 5, we have the bootstrap/js/dist
folder, which contains the source code for the individual JavaScript components, as well as the base-component.js
file and the dom
folder, with some more general code related to working with the DOM (the Document Object Model of the page).
We might imagine that we can just add one of these files in a <script>
tag in our HTML as follows:
HTML
<script src="node_modules/bootstrap/js/dist/modal.js"></script>
However, this won’t work. We’ll get an error in the browser console. We have to reference these files in our script.js
file and use a module bundler.
As an example, if we only import the bootstrap/js/dist/modal.js
file...