skip to Main Content

I have received 1 javascript file, lets call it "neededjavascriptfile.js", and it has a package.json file.
This javascript file will need to be run in a html index file, where I will need to use some functions from the javascript file.

I have ran "npm install –omit=dev" in the folder, and it has downloaded the required .js files and other files, and put them in a "node_modules" folder.

How does the javascript file know how to find these files? The node_modules folder seems to have a bunch of files, some which are probably not required.

What I have currently done is to go into each and every folder, and put the "filename.min.js", into my root folder, then I have included all the files in my "index.html" like below:

<script type="text/javascript" src="filename.min.js"></script>
<script type="text/javascript" src="filename2.min.js"></script>
<script type="text/javascript" src="neededjavascriptfile.js"></script>

There must be a better, and more correct way to do this?

2

Answers


  1. How does the javascript file know how to find these files?

    It doesn’t.

    npm is the Node Package Manager. It is designed for use with Node.js which, in turn, is designed to use the node_modules directory when you import modules without an explicit path.

    Browsers do not have that feature.

    If you want to involve npm in your build process for JS targetting browsers then you need to do something to give the JS files URLs on your web server.

    Typically that involves the use of a bundler like Parcel, Vite, or Webpack.

    Login or Signup to reply.
  2. The short answer: yes, there is a better way. Use a build tool like Rollup or Webpack to create a bundle that the web server can serve.

    The long answer: the Javascript that is running inside a web page doesn’t know anything about node_modules. There are two levels at work here: the first one is your development environment; the second is the deliverable that you want to create and execute (the web page, in this case).

    When you use npm you are developing a node application. If you run it with node, it knows where to find the dependencies in node_modules.

    On the other hand, if you include scripts in a web page (and remember this is happening on another machine), all the browser knows is how to reach the web server and the path you define in src is relative to the root folder of the server. You could do something "ugly" like changing the src attribute so that it points to ../node_modules/<etc>, or something like that (assuming the folder is accessible to the web server), but that is not recommended. That is why you have to manually do what a build tool like Rollup is designed to do (copying the files in the root folder, in this example).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search