Using CDN vs Installing the NPM Library

Although, I used NPM, but I do not understand how the files in node_modules are added to my index.html and work from there.

For example, if I need to use jQuery, it is that simple. I will get the file via cdn and add index.html to my 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 not adding cdns, but now I will include jQuery from NPM. I will create a package.json file and then add jQuery by going to the appropriate folder and typing:

CASE II: NPM folder - node_module

Now I have completed the following steps:

  • Created package.json npm init --yes

  • Enabled jQuery npm install jquery --save

Now the folder looks like this: enter image description here

Now that I have removed the jQuery cdn link, I don’t know how the "jQuery file" from node_modules will be added to my index.html?

Please someone help. I have no clue ... I am doing this in a browser!

+5
source share
3 answers

Cdn

Use a CDN if you are developing a website accessible to Internet users.

Benefits of CDN:

  • It will be cashed in most browsers because it is used by many other websites.

  • Reduce bandwidth

check additional benefits here

NPM

npm is a great tool for managing dependencies in your application using a package modulator .

Example:

suppose the webpack module and jQuery are installed

 import $ from 'jQuery' ... var content = $('#id').html(); 

but the browser does not understand the import statement, so you need to translate the code using the webpack commands, the linker will check all the dependencies used, linking them in one file without any dependency problems.

Useful Links: Getting Started with the Web Package

+2
source

Perhaps I misunderstood your question ... But can you just add this line to your index.html file?

 <script src="node_modules/jquery/dist/jquery.min.js"></script> 
+1
source

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

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

If you use Express, you can do something like this on the server side:

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

And then link to the file in index.html :

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

See Express' for serving static files .

If you are not using Express, you need to refer to the stack guide in your web server. It is impossible to guess, unfortunately, I gave an example of Express.js, because it is probably the most popular package for node.js.

0
source

Source: https://habr.com/ru/post/1267122/


All Articles