【问题标题】:How do I generate static HTML for my homepage from Create React App?如何从 Create React App 为我的主页生成静态 HTML?
【发布时间】:2021-06-26 18:09:55
【问题描述】:

我有一个 CRA,希望静态生成首页以缩短加载时间和 SEO。这个想法是运行一个 NodeJS 脚本,在 index.html 中呈现 App 文档。

这是我的代码:

const { renderToString } = require("react-dom/server");
const App = require('./App');
const content = `<html><body>${renderToString(App)}</body></html>`
const fs = require('fs');
fs.writeFileSync('../public/index.html', content);

但是,我在使用 NodeJS 运行它时遇到问题:

import React from 'react';
^^^^^^

SyntaxError: Cannot use import statement outside a module

显然,我必须构建源代码,但我不知道该怎么做。我正在使用 CRA 来构建我的 React 文件(实际上,我正在使用 react-app-rewired,所以如果我知道如何去做,我可以自定义构建过程)。

我应该怎么做才能让它工作?

【问题讨论】:

    标签: reactjs create-react-app server-side-rendering react-app-rewired static-site-generation


    【解决方案1】:

    错误来自节点:https://stackoverflow.com/a/59399717/13216797

    我知道这不是你的问题...但是使用 Nextjs 怎么样?

    即使没有节点环境,您也可以使用 "next export" 命令创建一个捆绑包,该捆绑包可以像静态文件一样工作,同时仍然可以响应...

    【讨论】:

    • 我知道 NextJS,但我已经有一个相当大的项目在生产中,我不能只用 NextJS 重写它。下次我会更聪明的。
    【解决方案2】:

    我最终使用了 puppeteer,只是保存了生成的客户端代码。在此之前,我花了几个小时先删除window,然后是window.location,然后是window.localStoragewindow.documentwindow.document.createElement,它从未结束。使用 puppeteer,这很容易。

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2018-09-12
      • 1970-01-01
      • 2018-02-14
      • 2019-12-12
      • 2018-02-11
      • 1970-01-01
      • 2020-10-08
      • 2019-04-27
      相关资源
      最近更新 更多