Lineserve

A Complete Guide to Including JavaScript Files in Another JS File: ES6 Modules, CommonJS, and More

Lineserve TeamLineserve Team
·
6 min read

Ever wondered how to pull in external JavaScript files into your main script, just like you do with CSS using @import? Whether you’re building a simple web app or a complex Node.js server, including one JS file in another is a fundamental skill. In this guide, we’ll explore various methods—from classic HTML script tags to modern ES6 modules and CommonJS—helping you understand when and how to use each approach. By the end, you’ll be equipped to modularize your code effectively and avoid common pitfalls.

Traditional Methods: Including JS Files via HTML

The simplest way to include external JavaScript files is by using HTML script tags. This method doesn’t involve including one JS file directly into another but rather loading them in your HTML document. It’s the go-to for beginners and still widely used in web development.

How It Works

You add <script> tags in your HTML file, specifying the source of the JS file. These scripts load and execute in the order they appear.

<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <script src="utils.js"></script>
  <script src="main.js"></script>
</body>
</html>

Here, utils.js loads first, followed by main.js. Inside main.js, you can access functions defined in utils.js.

Practical Example

Suppose you have a utility function for calculating squares in utils.js:

// utils.js
function square(number) {
  return number * number;
}

And you use it in main.js:

// main.js
const result = square(5);
console.log(result); // Outputs: 25

This approach works great for small projects without build tools.

Pros and Cons

  • Pros: Easy to implement, no special syntax needed, works in all browsers.
  • Cons: Global scope pollution (variables are shared), no built-in dependency management, can lead to performance issues with many files.

Use Case: Ideal for simple web pages or when using libraries like jQuery. Avoid for large-scale apps where modularity matters.

Modern Approach: ES6 Modules

ES6 introduced a native way to include JS files using import and export statements. This enables modular development in the browser, assuming your environment supports it (modern browsers or with a bundler like Webpack).

Exporting and Importing

Use export to make parts of a file available:

// utils.js
export function square(number) {
  return number * number;
}

export const PI = 3.14159;

Then import in another file:

// main.js
import { square, PI } from './utils.js';

const result = square(5);
console.log(result); // 25
console.log(PI); // 3.14159

You can also use default exports for a single main export:

// utils.js
export default function square(number) {
  return number * number;
}
// main.js
import square from './utils.js';
const result = square(5);
console.log(result);

Practical Example

Imagine building a calculator app. You could have a module for math operations and another for UI:

// math.js
export function add(a, b) {
  return a + b;
}
// ui.js
import { add } from './math.js';
export function displayResult(a, b) {
  console.log(`Result: ${add(a, b)}`);
}

Call it in your main script:

// app.js
import { displayResult } from './ui.js';
displayResult(2, 3); // Result: 5

Pros and Cons

  • Pros: Clean syntax, tree-shakable (only imports what’s needed), supports static analysis.
  • Cons: Requires type="module" in HTML script tags, not supported in older browsers without transpilation.

Use Case: Perfect for modern web apps, especially with frameworks like React. Combine with bundlers for production.

Node.js Standard: CommonJS

In Node.js environments, CommonJS is the traditional module system using require and module.exports.

How to Use It

Export from one file:

// utils.js
function square(number) {
  return number * number;
}

module.exports = { square };

Require in another:

// main.js
const { square } = require('./utils');
console.log(square(5)); // 25

You can also export a single function:

// utils.js
module.exports = function square(number) {
  return number * number;
};
// main.js
const square = require('./utils');
console.log(square(5));

Practical Example

Building a simple server with a utility for logging:

// logger.js
module.exports = function log(message) {
  console.log(`[LOG] ${message}`);
};
// server.js
const log = require('./logger');
log('Server started');

Pros and Cons

  • Pros: Synchronous loading, works out-of-the-box in Node.js, mature ecosystem.
  • Cons: Not as flexible as ES6 for browsers, can lead to slower startup with many requires.

Use Case: Essential for Node.js backends. If you’re working server-side, this is your default.

Advanced Technique: Dynamic Imports

For loading JS files conditionally or asynchronously, use dynamic imports. This is part of ES6 and works in both browsers and Node.js (with support).

Syntax and Usage

Use import() as a function that returns a promise:

// main.js
async function loadModule() {
  const { square } = await import('./utils.js');
  console.log(square(5)); // 25
}

loadModule();

Where utils.js has:

// utils.js
export function square(number) {
  return number * number;
}

Practical Example

Load a heavy module only when needed:

// app.js
if (userNeedsCalculator) {
  import('./calculator.js').then(module => {
    module.calculate();
  });
}

This improves performance by splitting code.

Pros and Cons

  • Pros: Asynchronous, reduces initial bundle size, enables code splitting.
  • Cons: Requires handling promises, not ideal for synchronous operations.

Use Case: Large apps needing lazy loading, like single-page applications.

Tips, Best Practices, and Common Pitfalls

Best Practices

  • Use ES6 modules for new projects to future-proof your code.
  • Always specify file paths relative to the importing file (e.g., ./utils.js).
  • Combine with bundlers like Webpack or Rollup for optimization in production.

Common Pitfalls

  • Avoid global variables in script tags: They can cause conflicts. Use modules instead.
  • Don’t mix module systems: Stick to one (e.g., ES6) to avoid confusion.
  • Watch for browser support: Use Babel for transpiling ES6 to compatible code.

Tip: For debugging, check browser console for import errors, and use tools like ESLint to enforce module rules.

Summary

In summary, including JavaScript files has evolved from basic script tags to sophisticated module systems like ES6 and CommonJS. Script tags are quick for beginners but lack modularity. ES6 modules offer clean, modern syntax for browsers, while CommonJS is king in Node.js. Dynamic imports add flexibility for performance. Choose based on your environment and project needs.

Next Steps

Now that you’re familiar with these methods, try refactoring a small project to use ES6 modules. Experiment with a bundler to see the benefits. For deeper dives, check out MDN’s module docs or Node.js guides. Happy coding!

Share:
Lineserve Team

Written by Lineserve Team

Related Posts

Lineserve

AI autonomous coding Limitation Gaps

Let me show you what people in the industry are actually saying about the gaps. The research paints a fascinating and sometimes contradictory picture: The Major Gaps People Are Identifying 1. The Productivity Paradox This is the most striking finding: experienced developers actually took 19% longer to complete tasks when using AI tools, despite expecting [&hellip;]

Stephen Ndegwa
·

How to Disable Email Sending in WordPress

WordPress sends emails for various events—user registrations, password resets, comment notifications, and more. While these emails are useful in production environments, there are scenarios where you might want to disable email sending entirely, such as during development, testing, or when migrating sites. This comprehensive guide covers multiple methods to disable WordPress email functionality, ranging from [&hellip;]

Stephen Ndegwa
·

How to Convert Windows Server Evaluation to Standard or Datacenter (2019, 2022, 2025)

This guide explains the correct and Microsoft-supported way to convert Windows Server Evaluation editions to Standard or Datacenter for Windows Server 2019, 2022, and 2025. It is written for: No retail or MAK keys are required for the conversion step. 1. Why Evaluation Conversion Fails for Many Users Common mistakes: Important rule: Evaluation → Full [&hellip;]

Stephen Ndegwa
·