Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between importing js library or reference it in html <script> tag

I am currently working with webpack with react js. I am new to it and have a question about the importing dependencies. In traditional way, we usually import a third party library from the <script> tag in html. Now I can do it in the javascript by running below code. I wonder what the difference between these two approaches is. Whether they are imported into a same namespace? Is there any other difference?

import $ from 'jquery'
import React from 'react';
import ReactDOM from 'react-dom';
import load from 'little-loader';
like image 422
Joey Yi Zhao Avatar asked Apr 12 '16 02:04

Joey Yi Zhao


People also ask

How do I import JavaScript into HTML?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

What is the difference between placing JavaScript code within the head tag and the body tag?

JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.

What does it mean by import in JS?

The import statement makes modular code possible in JavaScript (and also, code reuse and sharing). Without import or a similar mechanism, a developer could only write a JavaScript program as a single program in one file.

Can I use import in script tag?

In order to use the import declaration in a source file, the file must be interpreted by the runtime as a module. In HTML, this is done by adding type="module" to the <script> tag.


1 Answers

You'll notice that Webpack generates a JS file which is included via a <script> tag. This is the "bundled" file. You always have a <script> tag on the page.

What Webpack/Browserify/etc. do, is they take several different JS files and combine them into one JS file to load via a <script> tag. So this:

<script src="jquery.js" type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>

...becomes this:

<script src="bundle.js" type="text/javascript"></script>

jQuery and all your app.js code is now inside the bundle.js file. Webpack will also make sure that everything is in the right order, so that jQuery runs before the app.js code. That's why you have this line:

import $ from 'jquery'

...or in ECMAScript 5:

var $ = require('jquery');

This tells the bundler that you depend on jQuery, so it can make sure it is 1) included and 2) included in correct order.

like image 132
Steve Harrison Avatar answered Oct 30 '22 07:10

Steve Harrison