Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a module in in ES6 using import instead of require

Hi I am trying to add a module to my code. In ES5 I used

var promise = require('bluebird');

So I tried import { promise } from 'bluebird' but it didn't work any idea why?

like image 922
Muhammad Raihan Muhaimin Avatar asked Sep 15 '16 17:09

Muhammad Raihan Muhaimin


Video Answer


3 Answers

Generally to use import instead of require we should use some external modules, because Node.js doesn't support ES6's import yet.

To do so, we first have to install those modules babel-preset-es2015 and babel-cli.

npm install --save-dev babel-preset-es2015 babel-cli

Then we create a dot file called .babelrc where we add inside of it this object :

{
    "presets": ["es2015"]
}

Now we will be able to use import instead of require. For example, we can try on some server.js file this peace of code where we call express module using import instead of require:

import express from 'express'; //instead of const express = require('express');
const app = express();

app.get('/',function (req, res){
    res.send('hello from import');
});

app.listen(4444, function(){
    console.log('server running on port 4444');
});

Finally in our shell we will have to run this command:

./node_modules/.bin/babel-node app.js --presets es2015
like image 82
Taha EL BOUFFI Avatar answered Oct 15 '22 21:10

Taha EL BOUFFI


Actually import { promise } from 'bluebird' translated in es5 as var promise = require('bluebird').promise. So the equivalent of var promise = require('bluebird') in es6 would be import * as promise from 'bluebird'

EDIT: Based on the comment of @Bergi: import Promise from 'bluebird' is a more simplified version.

like image 23
Muhammad Raihan Muhaimin Avatar answered Oct 15 '22 21:10

Muhammad Raihan Muhaimin


In Greeter.js (put it into Scripts folder):

export class Greeter() {
    constructor() {

    }

    getGreeting() {
        alert('Hello from the greeter class');
    }
}

Call it:

<script>
    import {Greeter} from "/Scripts/Greeter.js";

    let greeter = new Greeter();
    greeter.getGreeting();
</script>
like image 38
Tân Avatar answered Oct 15 '22 22:10

Tân