Using ES6 Import/Export in Node.js & Babel.js

Using ES6 Import/Export in Node.js & Babel.js

This Node.js tutorial explains how to use ES6 Import/Export in Node.js & Babel.js. In this post we portray the `import` and `export` highlight in ES6 and how we are utilizing it as a part of Node.js v6 with `Babel.js`. ES6 acquainted another route with arranging modules. It's not the same as CommonJS and AMD we are as of now utilizing, which through the new catch phrases import and export

ES6 acquainted another route with arrange modules. It's not the same as CommonJS and AMD we are as of now utilizing, which through the new catchphrases import and export. It still NOT being bolstered by the most recent form of Node.js. Be that as it may, luckily we can influence Babel.js to play it at this moment.

When we are revamping the following form of Instant Message module of our creation - Worktile Pro, we utilized this element under Node.js v6 and Babel.js. So in this post I might want to present what it is and how I was utilizing.

Development Environment with Babel.js

Bebel.js is an open source JavaScript compiler which permits us to utilize most recent components, particularly something still in draft running in lower level runtime. For our situation, we require Babel.js to interpret and assemble our backend source code composed with ES6 and ES7 elements, to the code in ES6 that good with Node.js v6.

The following is a piece of the package.json document we are utilizing.

{
      "name": "Worktile Pro IM",
      "version": "1.0.0",
      "main": "app.js",
      "scripts": {
        "run": "babel-node app.js",
        "build": "babel . -d .dist --ignore=\"node_modules\""
      },
      "devDependencies": {
        "babel-cli": "*",
        "babel-core": "*",
        "babel-preset-es2015-node5": "*",
        "babel-preset-stage-3": "*",
        "babel-register": "*"
      }
    }

Additionally we require .babelrc record to characterize the practices of Babel.js as underneath.

    {
      "presets": ["es2015-node5", "stage-3"],
      "plugins": []
    }

You can duplicate this document and utilize npm install to set up your workplace. In the event that you need to run your code with Babel.js without assembling, you can straightforward use npm run-script run, then babel-cli will incorporate your source code and execute in memory. This is great when advancement yet not underway, since it will utilize a considerable measure memory and drawback the execution of your application. When you regard your code, you can run npm run-script build to give Babel.js a chance to assemble the source code to a yield organizer (For my situation it's ./.dist/) when you can node ./.dist/app.js.

For more data about Babel.js, babel-node and Babel-cli please allude to Babel's document.

Customary CommomJS

How about we make an exceptionally basic application with customary Node.js modules in CommonJS style. The following is calc.js record which will be utilized later.

'use strict';

    exports.name = 'calc';
    exports.add = (x, y) => {
        return x + y;
    };
    exports.subtract = (x, y) => {
        return x - y;
    };
    exports.multiple = (x, y) => {
        return x * y;
    };
    exports.divide = (x, y) => {
        return x / y;
    };

The following is the way we can utilize it.

  'use strict';

    const calc = require('./calc');

    const x = 3;
    const y = 5;

    console.log(`${calc.name}`);

    const result_add = calc.add(x, y);
    console.log(`${x} + ${y} = ${result_add}`);

    const result_subtract = calc.subtract(x, y);
    console.log(`${x} - ${y} = ${result_subtract}`);

    const result_multiple = calc.multiple(x, y);
    console.log(`${x} * ${y} = ${result_multiple}`);

    const result_divide = calc.divide(x, y);
    console.log(`${x} / ${y} = ${result_divide}`);

Since it's in ES5 language structure we can essentially execute by node app.js.

enter image description here

Send out Variables and Import

ES6 export works fundamentally the same as with the way we are utilizing already. Fundamentally we can utilize export watchword to any variables characterized in the module source code. For instance, we can send out name by utilizing export const name = 'calc';. So this module can be overhaul as underneath.

 'use strict';

    export const name = 'calc';

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

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

    export const multiple = (x, y) => {
        return x * y;
    };

    export const divide = (x, y) => {
        return x / y;
    };

At the point when utilizing this module we require import watchword. Comparable as require we have to determine the way of this module and dole out as a variable. At that point we can utilize capacities characterized in calc.js not surprisingly.

'use strict';

    import * as calc from './calc';

    const x = 3;
    const y = 5;

    console.log(`${calc.name}`);

    const result_add = calc.add(x, y);
    console.log(`${x} + ${y} = ${result_add}`);

    const result_subtract = calc.subtract(x, y);
    console.log(`${x} - ${y} = ${result_subtract}`);

    const result_multiple = calc.multiple(x, y);
    console.log(`${x} * ${y} = ${result_multiple}`);

    const result_divide = calc.divide(x, y);
    console.log(`${x} / ${y} = ${result_divide}`);

Since we are utilizing export and import watchwords which is NOT bolstered in Node.js v6, we will got mistake if simply run it by node app.js.

enter image description here

We require use Babel.js to arrange it to the code Node.js backings and run it by utilizing npm run-script run, and you can see it works.

enter image description here

In the code beneath, we utilize import * as calc, which implies it will import all variables this module sends out, as properties of calc. On the other hand we can simply import a few variables we need and utilize then as independent variables as beneath.

'use strict';

    import {name, add, subtract} from './calc';

    const x = 3;
    const y = 5;

    console.log(`${name}`);

    const result_add = add(x, y);
    console.log(`${x} + ${y} = ${result_add}`);

    const result_subtract = subtract(x, y);
    console.log(`${x} - ${y} = ${result_subtract}`);

enter image description here

Default Export

Once in a while we have to send out only one variable. For this situation we utilize export default. For instance, in the code beneath I wrapped all variables into one protest and sent out as default.

    'use strict';

    export default {
        name: 'calc',
        add: (x, y) => {
            return x + y;
        },
        subtract: (x, y) => {
            return x - y;
        },
        multiple: (x, y) => {
            return x * y;
        },
        divide: (x, y) => {
            return x / y;
        }
    };

Presently we can import it into a variable.

    'use strict';

    import calc from './calc';

    const x = 3;
    const y = 5;

    console.log(`${calc.name}`);

    const result_add = calc.add(x, y);
    console.log(`${x} + ${y} = ${result_add}`);

    const result_subtract = calc.subtract(x, y);
    console.log(`${x} - ${y} = ${result_subtract}`);

    const result_multiple = calc.multiple(x, y);
    console.log(`${x} * ${y} = ${result_multiple}`);

    const result_divide = calc.divide(x, y);
    console.log(`${x} / ${y} = ${result_divide}`);

enter image description here

Default fare is exceptionally valuable when sending out a class. For instance, the code beneath we characterized our calc.js as a class and fare. >Note when trading a class, do NOT attach semi-comma toward the end of the code.


    'use strict';

    export default class Calc {
        constructor (x, y) {
            this.x = x;
            this.y = y;
        }

        add () {
            return this.x + this.y;
        }

        subtract () {
            return this.x - this.y;
        }

        multiple () {
            return this.x * this.y;
        }

        divide () {
            return this.x / this.y;
        }
    }

The following is the code we are utilizing this class.

'use strict';

    import Calc from './calc';

    const x = 3;
    const y = 5;
    const calc = new Calc(x, y);

    const result_add = calc.add();
    console.log(`${x} + ${y} = ${result_add}`);

    const result_subtract = calc.subtract();
    console.log(`${x} - ${y} = ${result_subtract}`);

    const result_mutiple = calc.mutiple();
    console.log(`${x} * ${y} = ${result_mutiple}`);

    const result_divide = calc.divide();
    console.log(`${x} / ${y} = ${result_divide}`);

Summary

In this post I portrayed the import and export highlight in ES6 and how we are utilizing it as a part of Node.js v6 with Babel.js. Fundamentally it doesn't furnish significant improvement contrasting and the first CommonJS module framework. In any case, with the update of Node.js and web programs, this component ought to be utilized broadly and supplant current CommonJS and AMD I think.

JavaScript Nodejs Babel WebDev ES6

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

Hire NodeJs Developer

Looking to build dynamic, extensively featured, and full-fledged web applications? **[Hire NodeJs Developer](https://hourlydeveloper.io/hire-dedicated-node-js-developer/ "Hire NodeJs Developer")** to create a real-time, faster, and scalable...

Let's Write a JavaScript Library in ES6 using Webpack and Babel

Writing your own webpack configuration for a JavaScript library in ES6 and learn webpack along the way. In this blog we will learn how to create our own webpack configuration to bundle a small JavaScript utility library using webpack and babel. Let's create the source code for our library. For that we will be create two utility functions into two separate files in our source folder.

Destructuring in Javascript

Destructuring is a very simple concept in javascript, it allows you to pull out some variables from object/array, but it has a lot of features. Here are some cool things you can do with it!

What's new in all Modern JavaScript - ECMAScript(ES) from ES6 - ES11πŸ”₯

A brief overview of what is new in all Modern Javascript - ECMAScript(ES) versions: ES2015 (ES6), ES2016 (ES7), ES2017 (ES8), ES2018 (ES9), ES2019 (ES10), ES2020 (ES11). Javascript is on version 😍ES2020 (ES11)😍 already (ES is short for EcmaScript, the technical name for Javascript).