0

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_modules\bootstrap 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 2

1

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 the package.json file in the module that you import/require to figure out which file is the entry point.

In the case of bootstrap, you have the following lines in package.json

  "main": "dist/js/bootstrap.js",
  "module": "dist/js/bootstrap.esm.js",

(These lines might vary, I have taken those from GitHub)

This means that it will load the file listed at main in case require('boostrap') is used or at module if you do import * 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 and browser and could have additional aliases.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. I'm using vite. It did cross my mind at some point whether the package.json was being read while compiling the assets but I've never heard of it working that way before, so wanted to ask the question in a general context to see what people came up with.
-1

import * as bootstrap ... is taking all the exported modules and putting them in bootstrap object

If you open ./node_modules/bootstrap/dist/js/bootstrap.js, you'd find the export {some_func, some_func_2} which is exporting the intended objects and function.

1 Comment

Thanks. You are correct. But I did already work out that it was reading one of the files in the /dist directory. The point of the question is how does it know which one to load, and that is not a question you answered in this reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.