Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
To import a variable from another file in JavaScript:
A
, e.g. export const str = 'Hello world'
.B
as import { str } from './another-file.js'
.Here is an example of exporting two variables from a file called
another-file.js
.
// 👇️ named export export const str = 'Hello world'; // 👇️ named export export const str2 = 'one two three';
Here is how we would import the variables in a file called index.js
.
// 👇️ named import import {str, str2} from './another-file.js'; console.log(str); // 👉️ "Hello world" console.log(str2); // 👉️ "one two three"
Make sure to correct the path that points to the another-file.js
module if you
have to. The example assumes that another-file.js
and index.js
are located
in the same directory.
For example, if another-file.js
was located one directory up, you'd have to
import as import {str} from '../another-file.js'
.
The syntax we're using to export and import variables is called JavaScript modules.
The example above uses a named export and a named import.
The main difference between named and default exports and imports is that you can have multiple named exports per file, but you can only have a single default export.
Let's look at an example of how we would import a variable that was exported using a default export.
Here are the contents of another-file.js
.
const str = 'Hello world'; // 👇️ default export export default str;
And here is how we would import the variable using a default import.
// 👇️ default import import str from './another-file.js'; console.log(str); // 👉️ "Hello world"
Notice that we didn't wrap the import in curly braces.
We could have also used a different name when importing the variable, e.g.
fooBar
.
// 👇️ default import import fooBar from './another-file.js'; console.log(fooBar); // 👉️ "Hello world"
This works, but is confusing and should be avoided.
If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.
You can also mix and match. Here is an example of a file that uses both a default and a named export.
const str = 'Hello world'; // 👇️ default export export default str; // 👇️ named export export const num = 100;
And here is how you would import the two variables.
// 👇️ default and named imports import str, { num } from './another-file.js'; console.log(str); // 👉️ "Hello world" console.log(num); // 👉️ 100
We used a default import to import the str
variable and a named import to
import the num
variable.
Note that you can only have a single default export per file, but you can have as many named exports as necessary.