目前,我的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" }
导入可以在我的所有React组件文件中使用,而不能在server.js中使用。如何将服务器从require切换到Import?
因为代码是通过babel运行的,所以它可以在webpack中工作。您可以通过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" } }