目前我的nodejs服务器中的所有模块都被导入为require(),即:
let path = require('path');
let express = require('express');
let http = require('http');
let app = express();
然而,我所关注的教程将它们导入为:
import express from 'express'
import path from 'path'
引发错误:
SyntaxError: Unexpected token import
我的webpack.config.js设置为:
module: {
rules: [
{
test: /\.js?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
}
在bablerc中:
{
"presets": ["es2015", "react"]
}
我的软件包版本:
"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"
}
导入适用于我的所有反应组件文件,而不是server.js。如何将服务器切换到从require?
导入答案 0 :(得分:13)
它适用于webpack情况,因为代码是通过babel运行的。您可以通过babel运行node.js代码。
如果你没有,请安装babel cli
npm install --save-dev babel-cli
然后像这样运行你的代码:
./node_modules/.bin/babel-node server.js
或者将它放在package.json中。
{
"scripts": {
"start": "babel-node server.js"
}
}
答案 1 :(得分:3)
By default, you’ll be using ES5 and it’ll be required to use require (ja ja) 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.
1. npm install --save-dev babel-cli
2. npm install --save-dev babel-preset-es2015
3. Lets pull in both ‘babel-cli and babel preset es2015” as dev dependencies as well as add the .babelrc file
{
"presets": ["es2015"]
}
The issue was gone, if you do as above steps`enter code here`
more infor please see:https://codebrains.io/setting-up-express-with-es6-and-babel/