What is JavaScript Import and How to Import Modules

JavaScript import is a syntax that allows you to import functions, objects, or values from other modules or files1 You can use it in two ways:

  1. Static import: You can use the import statement at the top of your module file to import bindings that another module exports.
  2. Dynamic import: use the import() function-like expression to load a module asynchronously and dynamically into a non-module environment.

Syntax

The syntax of the import module is the following. It has many syntaxes because it depends on whether we import single or multiple contents from a file.

import defaultExport from 'module_name';
import * as name from 'module_name';
import { content } from 'module_name';
import { content as alias } from 'module_name';
import { content , content2 } from 'module_name';
import { content , content2 } from "module-name/path/to/specific/un-exported/file";
import { content , content2 as alias2 , [...] } from 'module_name';
import defaultExport, { content [ , [...] ] } from 'module_name';
import defaultExport, * as name from 'module_name';
import 'module_name';
var content = import('module_name');

The name parameter is the “module object,” which will be used as a namespace to refer to the exports.

The export parameters specify individually named exports, while the import * as name syntax imports all of them. Below are examples to clarify the syntax.

Create a project folder, and inside the project folder, create three files.

  1. app.js
  2. data.js
  3. start.js

Now, node.js is not supporting import-export Functionality by default. So, we need a babel transpiler to make working. 

We need to install two packages for that. So go to the terminal and type the following command to generate the package.json file.

npm init -y

Then we need to install two node modules. So type the following command.

npm install babel-register babel-preset-env --save-dev

It will install the modules inside the node_modules folder.

Now, write the following code inside the start.js file.

require('babel-register')({
 presets: ['env']
});

module.exports = require('./app.js')

We will run this file to run the import-export statement in the app.js file.

The next step is to write the following code inside the data.js file.

export const add = (x, y) => {
 return x + y
}

The add() function accepts the parameters, adds them, and returns the result.

Here the syntax is ES6, and we have used the arrow function.

Finally, add the following code inside the app.js file.

import { add } from './data';

console.log(add(2, 3));

Here, we have imported the data module and the specific add function from that module.

Now, run the start.js file and see the output.

node start.js

Javascript Import Statement Tutorial

We have imported a single export from a module in the above example.

If we have multiple export modules, then we can import various modules.

Import Multiple Modules in Javascript

Ee will create another module inside the data.js file.

export const add = (x, y) => {
  return x + y
}

export const subtract = (x, y) => {
  return x - y;
}

Now, import both of the modules inside the app.js file.

import { add, subtract } from './data';

console.log(`The addition is: ${add(2, 3)}`);
console.log(`The suntraction is: ${subtract(21, 19)}`);

Finally, run the start.js file and see the output.

Javascript Import Statement Tutorial With Example

Javascript Import with a more convenient alias

You can rename an export when importing it. For example, this inserts sub into the current scope.

See the app.js file. We have renamed the module subtracts to the sub.

import { add, subtract as sub } from './data';

console.log(`The addition is: ${add(2, 3)}`);
console.log(`The suntraction is: ${sub(21, 19)}`);

Importing defaults in Javascript

Let’s say; we only have one export default module inside the data.js file.

const add = (x, y) => {
   return x + y
}
export default add;

In the above code, we have used the export default keyword, which means we only export the add module from this file.

Now, if we have one default module inside a data.js file, we can import it inside the app.js file like below.

import add from './data';

console.log(`The addition is: ${add(2, 3)}`);

See the output below.

Importing defaults

Import * in Javascript

Usually, we list what to import in curly braces import {…}.

Create one file called client.js and add the following code.

const marvel = (hero) => {
 console.log(`Hello, ${hero}!`);
}

const dc = (hero) => {
 console.log(`Bye, ${hero}!`);
}

export {marvel, dc};

The client.js file exports two functions. So, we can import both functions inside the app.js file.

Now, add the following code inside the app.js file.

import * as superHeros from './client';

superHeros.marvel('Venom');
superHeros.dc('Wondar Woman');

So we have imported all the modules as superHeros.

See the output.

Hello, Venom!
Bye, Wondar Woman!

Dynamic Imports in Javascript

The import keyword may be called the function to import the module dynamically. When used this way, it returns the promise. Let’s see the example.

let app = await import('./data');
console.log(`The addition is: ${add(2, 3)}`);

It will give the same output. In the above code, we have used an async-await feature of ES7.

If you are new to that, then check out this article.

Dynamic import is helpful when you load the module conditionally or on demand.

The static form is preferable for initial loading dependencies and can benefit more readily from static analysis tools and tree shaking.

How to Fix UncaughtError: cannot use import statement outside a module

To fix the UncaughtError: cannot use import statement outside a module error, you must convert your script to an ECMAScript module.

Follow the below steps.

  1. Rename your file from .js to .mjs (for example, main.mjs instead of main.js). This tells the browser that the file is a module.

  2. Add the type="module" attribute to your script tag in your HTML file that references the JavaScript file:
    <script type="module" src="main.mjs"></script>
  3. Use the export statement to export any functions, variables, or objects that you want to make available to other modules:
    // In main.mjs
    export function add(a, b) {
    return a + b;
    }
  4. Use the import statement to import any functions, variables, or objects that you want to use from other modules:

    // In main.mjs
    import { add } from './math.mjs';
    console.log(add(2, 3)); // Output: 5

The error “Uncaught SyntaxError: Cannot use import statement outside a module” occurs in JavaScript when you try to use the import keyword in a script that is not a module. This error happens because the import statement is only allowed inside ECMAScript modules.

Conclusion

In JavaScript, import is a keyword to import modules or objects defined in other files. This allows you to use code from one file in another without copying and pasting the code into the new file.

To use import, you need to have a module defined in another file you want to use in your current file. The module needs to have an export statement, which specifies which objects or functions are available for import.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.