JavaScript

How to Include a JavaScript File in another JavaScript File

There are several ways to include a JavaScript file within another JavaScript file. In this tutorial, we will discover the different solutions.
 

How to Include a JavaScript File in another JavaScript File Using Old version of Javascript
Use the <script> tag in your HTML code:

This might be the most obvious way to solve this problem with the modern javascript framework.

When you import a .js file into your HTML code, the control is very important and you may think of the <script> tag as similar to an import. For example, if your script requires jQuery, you need to import the jQuery library first, then your script. Here is an example:

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>Write your script here!</script>

In the above code, your JS script can use any jQuery function.
 

 

How to Include a JavaScript File in another JavaScript File Using New version of Javascript
Using modern javascript ES6

We will use two files: file.js and main.js. We will use the import statement in main.js to import functions from file.js.

Contents of file.js:

export function sayWelcome() {
  return "Welcome to StackHowTo.com";
}

Contents of main.js:

import {sayWelcome} from 'file';
 
console.log(sayWelcome());

After executing the above code, you will see in the console “Welcome to StackHowTo.com”.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *