AppDividend
Latest Code Tutorials

Javascript Import: How to Import Modules In JavaScript

0

If you have a very complex app and have to scroll through hundreds or thousands of code lines, then the job of debugging or just understanding the app becomes much harder. Fortunately, Javascript helps us by having the ‘import‘ and ‘export‘.

Javascript Import

Javascript Import statement is used to import bindings that are exported by another module. Using the Javascript import, 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 a complex web app and have to scroll through the hundreds or thousands of code lines, then the job of debugging or just understanding an app becomes that much harder.

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 the frontend or backend, then an idea of imports and exports is the same, but the syntax is slightly 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 the script has a type=’ module.’

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

Dynamic import is 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 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')

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 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 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 {…}.

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 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.

#Fix: cannot use import statement outside a module

What is this cannot use import statement outside a module error and how to fix it.

It is an Uncaught syntax error. The issue is causing because the import statement is ES6 syntax, and node.js understands require module syntax. First, you need to compile your code to es5 and then run the node server file that way, and 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 many 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.

The static import statement is used to import bindings that are exported by another module. 

Imported modules are in strict mode whether you declare them as such or not.

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

Here is an example of the import statement with the type module.

type = “module”

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

At any given point in 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"YouAllAt 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.

There are a lot of reasons for the issue mentioned above to happen.

For example, you might have a source file in the src directory instead of the built file in the dist directory.

This means you’re using the native source code in the unaltered/unbundled state, leading to the following error: Uncaught SyntaxError: Cannot use import statement outside a module.

You can fix the issue by building the script file and importing them.

Another issue might be that you are loading the file which uses an es6 with normal js files; you should first compile an es6 and then load the files to fix the issue.

You can add the type=” module” with the script tag, and the issue was resolved.

Node.js latest version solution

Verify that you have the latest version of Node installed. If you have recently updated a Node version, then –experimental-modules flag is no longer necessary.

Follow any of the following options to fix the issue:

Add “type”: “module” to the nearest parent package.json.

With this, all .js and .mjs files are interpreted as ES modules. You can understand individual files as the CommonJS by using the .cjs extension.

OR

Explicitly name files with the .mjs extension.

All other files, such as .js, will be interpreted as a CommonJS, which is the default if the type is not defined in package.json.

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 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.