Question
How can I use code from one JavaScript file inside another JavaScript file, similar to how @import works in CSS?
For example, if I have one JavaScript file that defines reusable functions or variables, what is the correct way to make those available in another JavaScript file?
Short Answer
By the end of this page, you will understand that JavaScript does not traditionally "include" one file inside another the way CSS uses @import. Instead, JavaScript code is shared through file loading in HTML or through module systems such as ES modules. You will learn the difference between classic script loading and import/export, when to use each approach, and how this works in real projects.
Concept
JavaScript files are not usually inserted into each other by writing a special include statement inside the file itself. Instead, JavaScript code is made available in one of two common ways:
- Classic script loading using multiple
<script>tags in an HTML file. - Modules using
exportin one file andimportin another.
In older JavaScript, if you loaded multiple files in an HTML page, they shared the same global scope. That meant one file could define a function and another file could use it, as long as the files were loaded in the correct order.
In modern JavaScript, the preferred approach is ES modules. A module lets you explicitly choose what a file exposes and what another file imports. This makes code easier to understand, test, and maintain.
Why this matters:
- It helps you organize code across multiple files.
- It avoids putting too many variables in the global scope.
- It makes dependencies clear.
- It is the standard approach in modern frontend and backend JavaScript.
So the real concept is not "including a file inside another file," but sharing code between files in a structured way.
Mental Model
Think of each JavaScript file as a toolbox.
- In the old style, all toolboxes are dumped onto one shared workbench. If one file adds a hammer, another file can use it, but only if the hammer was placed there first.
- In the modern module style, each toolbox is closed by default. If you want another file to use a tool, you must label it with
export. The other file must then explicitly request it withimport.
This makes it much easier to know where each tool came from and prevents the workbench from becoming cluttered.
Syntax and Examples
1. Classic script loading
If you are working in a browser without modules, you can load multiple JavaScript files from HTML.
<script src="helpers.js"></script>
<script src="app.js"></script>
helpers.js
function greet(name) {
return `Hello, ${name}`;
}
app.js
console.log(greet("Sam"));
Because helpers.js is loaded first, app.js can use greet().
2. Modern ES modules
This is the preferred modern approach.
Step by Step Execution
Consider this module example:
// helpers.js
export function double(number) {
return number * 2;
}
// app.js
import { double } from './helpers.js';
const result = double(5);
console.log(result);
Here is what happens step by step:
-
The browser loads
app.jsbecause it was included with:<script type="module" src="app.js"></script> -
JavaScript sees this line:
import { double } from './helpers.js'; -
It loads .
Real World Use Cases
This concept is used everywhere in real JavaScript applications.
- Utility functions: Put shared helpers like formatting dates or validating email addresses in one file and import them where needed.
- API code: Keep network request logic in a separate file such as
api.jsand use it in UI components. - Configuration: Store constants like API URLs or app settings in one module.
- UI components: Split large frontend apps into many files, each exporting related code.
- Data processing scripts: Reuse parsing or transformation functions across multiple scripts.
- Node.js projects: Import functions, classes, or configuration files into route handlers, services, and utilities.
Example:
// config.js
export const API_BASE_URL = 'https://api.example.com';
// userService.js
import { API_BASE_URL } from './config.js';
console.log(`${API_BASE_URL}/users`);
Real Codebase Usage
In real projects, developers rarely keep everything in one file. Instead, they break code into focused modules.
Common patterns include:
Guard clauses and validation
export function validateUser(user) {
if (!user) {
throw new Error('User is required');
}
if (!user.email) {
return false;
}
return true;
}
This can then be imported wherever user data is checked.
Centralized configuration
// settings.js
export const MAX_RETRIES = 3;
export const TIMEOUT_MS = 5000;
Grouped utility modules
// stringUtils.js
export function capitalize(text) {
text.().() + text.();
}
() {
text.().(, );
}
Common Mistakes
1. Expecting an @import-style include inside plain JavaScript
JavaScript does not work like CSS in this way. You usually either:
- load files from HTML, or
- use
import/export
2. Loading files in the wrong order with classic scripts
Broken example:
<script src="app.js"></script>
<script src="helpers.js"></script>
// app.js
console.log(greet("Sam"));
This fails because greet is not defined yet.
Fix:
<script src="helpers.js"></script>
< =>
Comparisons
| Approach | How it works | Best for | Pros | Cons |
|---|---|---|---|---|
Classic <script> tags | Load files in HTML; all share global scope | Very small or older browser examples | Simple to start with | Order matters, globals can clash |
ES modules (import/export) | Files explicitly share exported values | Modern frontend and backend JavaScript | Clear dependencies, modular code | Requires module-aware environment |
| Copy-pasting code | Duplicate logic across files | Almost never a good choice | Fast for a quick test | Hard to maintain, error-prone |
Named export vs default export
Cheat Sheet
Quick reference
Classic browser loading
<script src="file1.js"></script>
<script src="file2.js"></script>
- Files are loaded in order.
- Earlier files can define globals used by later files.
- Avoid this for large applications.
ES modules
Export from one file:
export const value = 123;
export function greet(name) {
return `Hello, ${name}`;
}
Import into another file:
import { value, greet } from './helpers.js';
Default export
export default () {
a + b;
}
FAQ
Can I include one JavaScript file directly inside another?
Not in the old CSS-like sense. The usual approaches are loading both files in HTML or using ES modules with import and export.
What is the modern way to share code between JavaScript files?
Use ES modules. Export values from one file and import them into another.
Why does my import statement not work in the browser?
Common reasons include missing type="module", wrong file path, or forgetting to export the value.
Do I need to include .js in import paths?
In browser ES modules, yes, you usually include the file extension for local files.
What is the difference between named and default exports?
Named exports let a file expose multiple values. A default export is usually the main value from a file.
Can multiple files use the same helper function?
Yes. Put the helper in one module, export it, and import it wherever needed.
Is using global variables across script files a good idea?
Usually no. It works in simple cases, but modules are safer and easier to maintain.
Mini Project
Description
Build a small reusable utility setup with two JavaScript files. One file will contain helper functions, and the other will import and use them. This demonstrates the modern way to share code between files without relying on global variables.
Goal
Create a simple app that imports functions from another file and uses them to format and process text.
Requirements
- Create one file that exports at least two helper functions.
- Create a second file that imports and uses those functions.
- Load the second file in the browser as a module.
- Display the results in the console.
- Use correct relative import paths.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.