Near the top of my app.js
file, I have the line
import * as bootstrap from '../../node_modules/bootstrap';
If I console.log(bootstrap)
on the next line, then I can see that the bootstrap
variable does indeed hold a bootstrap-looking object with all the properties I’d expect.
The question is though, how does this work, because node_modulesbootstrap
is just a directory
|- node_modules
|-> bootstrap
|-> dist [dir]
|-> js [dir]
|-> scss [dir]
|-> LICENCE [txt file]
|-> package.json
|-> README.md
So how exactly does it work out what needs to be imported into the bootstrap
variable?
It’s more curiosity as to how this works really, because it does work correctly.
EDIT: (directory structure was edited since original post)
2
Answers
import * as bootstrap ...
is taking all the exported modules and putting them inbootstrap
objectIf you open
./node_modules/bootstrap/dist/js/bootstrap.js
, you’d find theexport {some_func, some_func_2}
which is exporting the intended objects and function.How
import
looks for a particular file depends on the environment. But if you use node or a common bundler like webpack, rollup, or vite, then those use thepackage.json
file in the module that youimport
/require
to figure out which file is the entry point.In the case of bootstrap, you have the following lines in
package.json
(These lines might vary, I have taken those from GitHub)
This means that it will load the file listed at
main
in caserequire('boostrap')
is used or atmodule
if you doimport * as bootstrap from 'boostrap'
. In those files, you could see what is exported.There could even be more entires that e.g. differentiate between
node
andbrowser
and could have additional aliases.