'Using Import In NodeJS server
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?
Solution 1:[1]
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"
}
}
Solution 2:[2]
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-clinpm install --save-dev babel-preset-es2015- Let's pull in both babel-cli and babel preset es2015 as dev dependencies as well as add the
.babelrcfile:
{
"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/
Solution 3:[3]
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",
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michel Kansou |
| Solution 2 | Renaat De Muynck |
| Solution 3 | Muhammad Osama |
