Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token import - Express

I have this in my index.js

import express from 'express'
import data from './data/data'


const app = express();
const PORT = 3000; 

app.listen(PORT, () =>
    console.log(`Your server is running on ${PORT}`)
);

This is my package.json

{
    "name": "express-app",
    "version": "1.0.0",
    "description": "backend provisioning",
    "main": "app.js",
    "scripts": {
        "start": "nodemon ./index.js --exec babel-node -e js"
    },
    "author": "B",
    "license": "ISC",
    "devDependencies": {
        "babel-cli": "^6.26.0",
        "babel-preset-env": "^1.6.1",
        "babel-preset-stage-0": "^6.24.1"
    },
    "dependencies": {
        "express": "^4.16.3"
    }
}

When I run nodemon , I got

[nodemon] 1.17.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
/Users/b/Desktop/express-app/index.js:1
(function (exports, require, module, __filename, __dirname) { import express from 'express'
                                                            ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:607:28)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...

Did I forget to do anything to be able to use the import command?

I did this :

npm install --save-dev babel-cli babel-preset-env babel-preset-stage-0
npm install express
nodemon

same result

I also try this

rm -rf node_modules/
npm install
nodemon

same result


.babelrc

{
    "presets":[
        "env",
        "stage-0"
    ]
}
like image 952
code-8 Avatar asked Apr 13 '18 16:04

code-8


2 Answers

NodeJS supports import natively only experimentally, and only if your script has the .mjs extension.

That's why the start in your package.json is referring to babel-node, which transpiles ES6 code into classic JS on-the-fly before running it. But I doubt even that command will work, because you're not passing any presets to babel to run the script. Try this command:

nodemon --exec babel-node --presets env index.js

[OR]

Rename your file to have .mjs extension, then run this:

nodemon --experimental-modules index.mjs

like image 198
Vasan Avatar answered Oct 02 '22 21:10

Vasan


This happens if you have lower version of node. please upgrade it to at least v10.0

like image 42
ritesh Avatar answered Oct 02 '22 20:10

ritesh