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

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

Using ES6 Import/Export in Node.js & Babel.js
1 Likes97.05 GEEK