在我的项目中导入React js期间,出现如下错误:
error : /Users/shivakrishna/reactRender/server.js:1
(function (exports, require, module, __filename, __dirname) { import React from 'react';
SyntaxError: Unexpected identifier
at new Script (vm.js:84:7)
at createScript (vm.js:264:10)
at Object.runInThisContext (vm.js:312:10)
at Module._compile (internal/modules/cjs/loader.js:694:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:745:10)
at Module.load (internal/modules/cjs/loader.js:626:32)
at tryModuleLoad (internal/modules/cjs/loader.js:566:12)
at Function.Module._load (internal/modules/cjs/loader.js:558:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:797:12)
at executeUserCode (internal/bootstrap/node.js:526:15)
代码如下:
server.js:
import React from 'react';
const express = require('express')
const ReactDomServer = require('react-dom/server');
const app = express();
app.use(express.static('build'))
app.get('*',(req,res)=>{
})
app.listen(3000,()=>{ })
webpack.sever.js :
const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');
module.exports = {
target : "node" ,
entry : './server.js',
output :{
filename : 'bundle.js',
path : path.resolve(__dirname,'build'),
publicPath :'/build'
},
module:{
rules:[{
test :/\.jsx$/ ,
loader :'babel-loader',
exclude:'/node_modules/',
presets :[
'react',
'stage-0',
['env',{
target : {browser : ['last 2 versions']}
}]
]
}],
},
externals :[webpackNodeExternals()]
}
package.json:
{
"name": "reactrender",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"webpack:server": "webpack --config webpack.server.js --watch",
"webpack:start": "nodeman --watch build --exec node build/bundle.js",
"dev": "npm-run-all --parallel webpack:*"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.6",
"babel-polyfill": "^6.26.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2017": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"nodeman": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-router": "^5.0.1",
"react-router-dom": "^5.0.1",
"webpack": "^4.35.2",
"webpack-cli": "^3.3.5",
"webpack-node-externals": "^1.7.2"
},
"devDependencies": {
"@babel/core": "^7.5.0",
"@babel/preset-env": "^7.5.0",
"@babel/register": "^7.4.4",
"babel-plugin-dynamic-import-node": "^2.3.0",
"babel-preset-env": "^1.7.0"
}
}