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';
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With