Using CDN vs Installing the Library by NPM

advertisements

Though, I have been using NPM, but I do not understand how the files in the node_modules are added to my index.html and work from there.

For Example, if I have to use jQuery, its so simple. I will get the file through cdn and add in my index.html file

CASE I: CDN

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<html>

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$('body').css('background','red');
});
</script>
</body>
</html> 

Now, I am adding not by cdns, but I will now include jQuery by NPM. I will create a package.json file and then add jQuery by going to the respective folder and type:

CASE II: NPM - node_module folder

I have now done the followign steps:

  1. Created package.json by npm init --yes

  2. Included jQuery by npm install jquery --save

Now, by folder looks like this:

Now, as I have now removed cdn link of jQuery, I dont know how will 'jQuery file' from node_modules will be added to my index.html?

Please, someone help. I have no clue ...I am doing this on browser!


I think you want to host jQuery yourself and use it within a web app running in the browser.

If so, you need to host this file - make it downloadable via the same web server you are using to host index.html.

If you are using Express, you might do something like this on the server side:

app.use('jquery', express.static(__dirname + '/node_modules/jquery/dist/'));

And then reference the file in index.html:

<script src="/jquery/jquery.js"></script>

See Express' manual for serving static files.

If you're not using Express, you need to consult your web server's stack manual. No way to guess unfortunately - I gave an Express.js example because this is probably the single most popular package like that for node.js.