0

我正在尝试服务器渲染一个反应应用程序,我使用预设环境配置了 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;
4

1 回答 1

0

我在服务器端使用 babel,我的 package.json 有那些 babel 相关的包。

"scripts": {  
    "babel-node": "babel-node ",     
    "start": "nodemon --exec npm run babel-node -- ./app.js",
  },

  "devDependencies": {
    "babel-polyfill": "^6.26.0",
    "babel-cli": "^6.26.0",
    "babel-eslint": "^8.2.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-latest": "^6.24.1",
    "babel-register": "^6.26.0",
  }

对于预设,我创建了 .babelrc 文件

{
  "presets": ["env"],

  "plugins": [
    [
      "transform-runtime",
      {
        "polyfill": false,
        "regenerator": true
      }
    ],   
  ]
 }

希望能帮助到你

于 2020-02-10T12:14:35.940 回答