AppDividend
Latest Code Tutorials

Javascript Import Example | How To Import Modules In JS

0

Javascript Import statement is used to import bindings that are exported by another module. If you have a very complex app and have to scroll through hundreds or thousands of lines of code, then a job of debugging or just understanding the app becomes much harder. Fortunately, Javascript helps us by having the ‘imports’ and ‘exports.’

Javascript Import

Using the Javascript import statement, the code is easier to manage when it is small and bite-size chunks.

This is the thinking behind keeping functions to only one task or having files contain only a few or one component at a time.

If you have the complex web app and have to scroll through the hundreds or thousands of lines of code, then the job of debugging or just understanding an app becomes that much harder.

Luckily for us, Javascript helps us out with this by having ‘imports’ and ‘exports’.

This is how you can write code in one file and share that code so another file or files can use it.

If you are using the ES6 syntax in frontend or backend, then an idea of imports and exports is the same, but the syntax is a little bit different.

Instead of ‘require’ at the top of the file, you now use the ‘import’ statement, and you can also have an ‘export default or export’ statement instead of module.exports. If you only have one thing to export out of a file or multiple modules.

The import statement cannot be used in the embedded scripts unless such the script has a type=’module.’

There is also function-like dynamic import(), which does not require scripts of type=’module.’

Dynamic import is pretty much useful in situations where you wish to load the module conditionally, or on-demand module. The static form is preferable for an initial loading dependency.

The syntax of the import module is following. It has so many syntaxes we can say because it is depending on if we are importing a single content 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 name of the “module object,” which will be used as a kind of 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 first 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.

// start.js

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

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

So, we will run this file, and it will allow us 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.

// data.js

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

The add function accepts the parameters and adds them and returns the result. Here is syntax is ES6, and we have used the arrow function.

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

// app.js

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

In the above example, we have used an Import a single export from a module.

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

#Import Multiple Modules in Javascript

Now, we will create another module inside the data.js file.

// data.js

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.

// app.js

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 subtract to 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 say; we only have one export default module inside the data.js file.

// data.js

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

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

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

// app.js

import add from './data';

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

See the output below.

Importing defaults

#Import * in Javascript

Usually, we put the list of what to import in curly braces import {…}, like this.

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

// client.js

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.

// app.js

import * as superHeros from './client';

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

So we have imported all the modules as superHeros.

See the output.

➜  es git:(master) ✗ node start
Hello, Venom!
Bye, Wondar Woman!
➜  es git:(master) ✗

#Dynamic Imports in Javascript

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

// app.js

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 useful in situations where you wish to 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.

#cannot use import statement outside a module

It is an Uncaught syntax error. The issue is causing because the import statement is ES6 syntax, and node.js understands require module syntax. So, first, you need to compile your code to es5 and then run the node server file that way, it will work fine.

All the major browsers now support ES6 Modules natively! I have begun some simple tests to get started and guess what, immediately ran into issues.

It seems like a lot of random talks out there around Javascript Modules are actually about how products like Webpack or Babel use the Modules architecture, and there are subtle and crucial differences compared to how it’s been implemented in the native JavaScript.

type = “module”

The great thing about Javascript Modules is that you can import and export Functionality between files.

At any given point of time, your main HTML file will have to have at least one script tag that loads your main javascript file. Your script tag, in this case, has to have the new type attribute equal to the module, like this:

<script src="main.js" type="module"></script>

If you don’t include type="module", you will get a lot of different troubles and errors that are incredibly confusing.

Firefox

SyntaxError: import declarations may only appear at top level of a module

Chrome

Uncaught SyntaxError: Unexpected identifier

Edge

SCRIPT1086: SCRIPT1086: Module import or export statement unexpected here

So, add the type="module" to your script tag.

Conclusion

Here are all types of import-export in Javascript.

Export

Before the declaration of a class/function/…:

export [default] class/function/variable …

Standalone export:

export {x [as y], …}.

Re-export:

export {x [as y], …} from “module”
export * from “module” (doesn’t re-export default).
export {default [as y]} from “module” (re-export default).

Import:

Named exports from the module:

import {x [as y], …} from “module”

Default export:

import x from “module”import {default as x} from “module”

Everything:

import * as obj from “module”

Import the module (its code runs), but do not assign it to a variable:

import “module”

You can refer more to Javascript imports on MDN.

So in this example, we have seen how to use javascript import statements, export statements, dynamic imports.

Finally, Javascript Import Example | Import Modules In Javascript Tutorial is over.

People Also Search

Javascript Date Methods and Objects

Javascript Array Values

Javascript Object.values()

Javascript Async / Await

Javascript Array includes()

Leave A Reply

Your email address will not be published.

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