AppDividend
Latest Code Tutorials

Javascript Import Statement Tutorial With Example

0

Javascript Import Statement Tutorial With Example is today’s topic. The static import statement is used to import bindings which are exported by the 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 Statement Tutorial

If you are using an 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’ in the top of the file, you now use ‘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 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.

Next step is to write a following code inside the data.js file.

// data.js

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

The add function accepts the parameters and add them and return 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 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

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

Import an export 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

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.

Finally, Javascript Import Statement Tutorial With Example is over.

Leave A Reply

Your email address will not be published.

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