There are several ways to include a JavaScript file in another JavaScript file.

Using the <script> tag: You can use the <script> tag to include a JavaScript file in an HTML file. The JavaScript file is loaded and executed when the page is loaded by the browser.

<script src="path/to/file.js"></script>

Using the import statement: The import statement allows you to import a JavaScript file in another JavaScript file. It is supported by modern browsers and Node.js. It is important to note that this only works if the JavaScript files are loaded in the same order.

// file1.js
import { func1 } from './file2.js';
func1();
// file2.js
export function func1() {
  console.log('Hello World!');
}

Using the require() function: The require() function allows you to include a JavaScript file in another JavaScript file. It is supported by Node.js and is often used in conjunction with a module bundler like webpack.

// file1.js
const func1 = require('./file2.js');
func1();
// file2.js
module.exports = function func1() {
  console.log('Hello World!');
}

Using the <link> tag: You can use the <link> tag to include a JavaScript file in a HTML file. The JavaScript file is loaded and executed when the page is loaded by the browser, but it also allows you to use the file as a stylesheet.

<link rel="javascript" href="path/to/file.js">

It’s worth noting that the <script>, import statement and require() function can only be used in JavaScript files, and the <link> tag can only be used in HTML files.

You can use any of these methods depending on your requirement, but the import statement and require() function are more suitable for large projects where the code is divided into multiple files and the <script> tag is more suitable for small projects.

Also Read:

Categorized in: