在 NodeJS 服务器中使用导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42645548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Import In NodeJS server
提问by Codematcha
At the moment all my module in my nodejs server are imported as require() ie:
目前,我的 nodejs 服务器中的所有模块都作为 require() 导入,即:
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:
我的 webpack.config.js 设置为:
module: {
rules: [
{
test: /\.js?$/,
use: 'babel-loader',
exclude: /node_modules/
}
]
}
In bablerc:
在 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?
导入适用于我所有的 react 组件文件,但不适用于 server.js。如何将我的服务器切换到从 require 导入?
回答by Brigand
It works in the webpack situation because the code is run through babel. You can run your node.js code through babel.
它适用于 webpack 情况,因为代码是通过 babel 运行的。你可以通过 babel 运行你的 node.js 代码。
Install the babel cli if you don't have it
如果你没有安装 babel cli
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.
或者把它放在 package.json 中。
{
"scripts": {
"start": "babel-node server.js"
}
}
回答by Dave
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/

