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?

1
  • 3
    import Promise from 'bluebird' should do? Commented Sep 15, 2016 at 17:04

4 Answers 4

15

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 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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> 

3 Comments

What does Greeter have to do with Bluebird?
@Bergi Oh sorry, I just give an example how to call a module via using import keyword.
@HappyCoding I used bluebird just an example. So it is alright.
0

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

node --es-module-specifier-resolution=node index.js 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.