At the moment all my module in my nodejs server are imported as require() ie:
let path = require('path');
let express = require('express');
let http = require('http');
let app = express();
However the tutorial I am following shows them imported as:
import express from 'express'
import path from 'path'
Which throws the error:
SyntaxError: Unexpected token import
My webpack.config.js is set up as:
module: {
rules: [
{
test: /\.js?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
}
In bablerc:
{
"presets": ["es2015", "react"]
}
My package versions:
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.1",
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-preset-env": "0.0.3",
"webpack": "^2.2.1",
"webpack-dev-middleware": "^1.10.1",
"webpack-dev-server": "^2.4.1",
"webpack-hot-middleware": "^2.17.1"
}
Import works in all my react components files, just not server.js. How do I switch my server over to Import from require?
The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error. Do not worry about the error!
The first method to use the “import” statement in JavaScript is to save the JavaScript file with the “. mjs” extension, instead of using the typical “. js” extension. Node.
Node 14 introduces ECMAScript modules — no more transpiling, no more difficulties with import and export.
It works in the webpack situation because the code is run through babel. You can run your node.js code through babel.
Install the babel cli if you don't have it
npm install --save-dev babel-cli
Then run your code like this:
./node_modules/.bin/babel-node server.js
Or put it in package.json.
{
"scripts": {
"start": "babel-node server.js"
}
}
By default, you’ll be using ES5, and it’ll be required to use require
to pull in modules. As we move forward with ES6 and beyond, it’s really best for us to start using ES6 classes as well as import and export statements. To do this, we’ll need Babel in order to interpret our ES6 syntax.
npm install --save-dev babel-cli
npm install --save-dev babel-preset-es2015
.babelrc
file:{
"presets": ["es2015"]
}
The issue should be gone, if you follow above steps
For more information please see: https://codebrains.io/setting-up-express-with-es6-and-babel/
Update 2022:
You can now use "type": "module"
in your package.json file and this will enable the ES6 import. No extra installations needed.
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
...
}
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