ES6 import statements not working in Node v8.4.0

前端 未结 2 980
独厮守ぢ
独厮守ぢ 2021-02-14 16:47

I\'m using the latest version of Node.js that is v8.4.0. However, in the import and export statements, I\'m getting errors:

import express from \'express\';
             


        
相关标签:
2条回答
  • 2021-02-14 17:02

    One way that I have worked around this issue...

    Install babel stuff for the project:

    $ npm install babel-register babel-preset-es2015 --save-dev
    

    Create an index.js file that is the main entry point into the app:

    // index.js 
    // by requiring `babel/register`, all of our successive `require`s will be Babel'd
    require('babel-register')({
       presets: [ 'es2015' ]
    });
    
    require('./server');
    

    Then, create a file called server.js that will have your normal index code:

    // server.js
    import express from 'express';
    
    var app = express()
    
    app.get('/', (req, res) => res.send('Hello World!'))
    
    app.listen(3000, () => console.log('Example app listening on port 3000!'))
    

    And run:

    $ node index.js 
    
    0 讨论(0)
  • 2021-02-14 17:16

    const express = require('express'); is the right syntax as some es6 features ie import express from express is currently not available with node!

    0 讨论(0)
提交回复
热议问题