Add a module in in ES6 using import instead of require
Asked Answered
A

4

12

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?

Arrack answered 15/9, 2016 at 17:2 Comment(1)
import Promise from 'bluebird' should do?Nuremberg
A
12

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.

Arrack answered 15/9, 2016 at 17:2 Comment(0)
M
16

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
Millicent answered 2/4, 2018 at 9:51 Comment(0)
A
12

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.

Arrack answered 15/9, 2016 at 17:2 Comment(0)
M
2

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>
Missend answered 15/9, 2016 at 17:23 Comment(3)
What does Greeter have to do with Bluebird?Nuremberg
@Nuremberg Oh sorry, I just give an example how to call a module via using import keyword.Mameluke
@HappyCoding I used bluebird just an example. So it is alright.Arrack
O
0

Use this flag: --es-module-specifier-resolution=node

node --es-module-specifier-resolution=node index.js
Oestradiol answered 17/2 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.