简体   繁体   中英

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?

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

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM