我正在尝试服务器渲染一个反应应用程序,我使用预设环境配置了 babel 以允许使用 import 语句,但它似乎不起作用,当我启动服务器时出现此错误:SyntaxError: Cannot use import statement outside a module
包.json:
"babel": {
"presets": [
"react",
"env",
"stage-2"
]
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"eslint": "^3.19.0",
"eslint-plugin-react": "^6.10.3",
"jest": "^19.0.2"
},
"dependencies": {
"babel-cli": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"ejs": "^2.5.6",
"express": "^4.15.2",
"pm2": "^2.4.6",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"webpack": "^2.5.0"
服务器.js:
app.use("/", (req,res)=>{
const initialContent = serverRender();
res.render("index",{initialContent});
});
服务器渲染.js:
import React from "react";
import ReactDOMServer from "react-dom/server";
import App from "./components/app";
const serverRender =()=>{
return ReactDOMServer.renderToString(<App/>);
};
export default serverRender;