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"
]
}
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
This happens if you have lower version of node. please upgrade it to at least v10.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With