If you are working in Javascript. And at that time you have to insert or add code from some other file in some file then what will you do? In this tutorial, you will learn how to include a JavaScript file in another JavaScript file.
How to include a JavaScript file in another JavaScript file?
There are some methods available in JavaScript for this and you can also do it by writing some custom code. With the help of the methods given below, you can include JavaScript file in a file in another JavaScript file:
- Method 1: Using HTML script tag
- Method 2: Using the “import” statement
- Method 3: Using the “require” function
Method 1: Using HTML script tag
The list you are putting in HTML and the file you are including in the code of a JavaScript file. For this, you can use a script tag.
In the HTML file where you want to include the JavaScript file, add the following script tag within the head or body section:
<script src="path/to/abc.js"></script>
Method 2: Using the “import” statement
If you are working with modern javascript and js6. Then you can use the import method of JavaScript to include a js file in another js file.
Here is an example of an import function to include one JavaScript file in another JavaScript file; as follows:
import { functionName } from './abc.js';
Replace “functionName” with the actual function you want to import, and ‘./abc.js’ with the correct relative path to the “abc.js” file.
Method 3: Using the “require” function
If you’re working with Node.js or using a build tool like Webpack or Browserify, you can use the “require” function to include JavaScript files.
Here’s an example of a require function to include a JavaScript file in another JavaScript file:
const utilities = require('./abc.js');
Replace ‘./abc.js’ with the correct relative path to the “abc.js” file. The “require” function will load the JavaScript file and assign its exports to the “abc” variable.