JavaScript provides multiple ways to include code from one file in another. The approach depends on whether you are working with modern JavaScript modules, Node.js CommonJS, or a simple browser-based application.
- Use import and export for modern JavaScript modules.
- Use require() with the CommonJS module system.
- Use <script> tags for simple browser-based applications.
Approach 1: Using ES6 Modules (import and export)
ES6 modules allow you to export functions, variables, classes, and other values from one JavaScript file and import them into another.
Create a math.js file and import the exported values into main.js:
// math.js
export function add(n1, n2) {
return n1 + n2;
}
export const pi = 3.14159;
// main.js
import { add, pi } from "./math.js";
console.log(add(2, 3));
console.log(pi);
Output
5
3.14159
- export makes add() and pi available to other modules.
- import loads the exported values into main.js.
- The ./ specifies that math.js is located in the same directory.
For browser-based applications, include the main file using:
<script type="module" src="main.js"></script>Note: In Node.js, ES6 modules can be used with the .mjs extension or by setting "type": "module" in package.json.
Approach 2: Using require() Method
The require() method is used with the CommonJS module system, which is commonly used in Node.js.
Create a math.js file and import the module into main.js:
// math.js
function add(n1, n2) {
return n1 + n2;
}
const pi = 3.14159;
module.exports = { add, pi };
// main.js
const { add, pi } = require("./math.js");
console.log(add(2, 3));
console.log(pi);
Output
5
3.14159
- module.exports exports the required values.
- require() imports the module into another file.
- Destructuring extracts add and pi from the imported object.
Approach 3: Using <script> Tags
In a simple browser-based application, multiple JavaScript files can be included using <script> tags in an HTML file.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript File Inclusion</title>
<script src="math.js"></script>
<script src="main.js"></script>
</head>
<body>
<h1>JavaScript File Inclusion</h1>
</body>
</html>
- The browser loads math.js first.
- main.js is loaded afterward.
- The order is important when main.js depends on code defined in math.js.
For example:
<script src="math.js"></script>
<script src="main.js"></script>
Here, math.js must be loaded before main.js if main.js uses functions defined in math.js.