简体   繁体   中英

Static site generator that renders React to HTML directly (no React in output)?

Can Gatsby or Jekyll or any other static site generators render a React-authored site into purely static HTML? I'm looking to host on S3/CloudFront or similar and also have little to no JS in the output.

Basically I'm looking to create a static website but would like to use React as development tool to take advantage of reusable UI components. Actual runtime interaction is minimal and can be done without React at runtime.

I looked at react-static which seems to be exactly what I'm looking for but the rendered html pages still reference and load the React library.

With my minimal needs I could probably roll my own thing to create each page as a separate React SPA and then use ReactDOMServer to render each to a static HTML file. I'm looking to see if there are simpler/better options.

You can use pupeteer to get the rendered html of any webpage, including SPA. Or use rendertron, which uses pupeteer underneath. Another one is react-snap, which will crawl your web on build and create the html for each page.

With Gatsby, sure you can. Gatsby has a html.js that serves as a template for all generated pages. You can simply remove Gatsby's javascript from that html.

/* Generated html */
...
<body>
  <div id="___gatsby">...</div>
  <script src="/common.js"></script> <-- remove this
</body>

First copy the default html to your src:

cp .cache/default-html.js src/html.js

Then, edit this line:

/* src/html.js */

    <body {...this.props.bodyAttributes}>
      {this.props.preBodyComponents}
      <div
        key={`body`}
        id="___gatsby"
        dangerouslySetInnerHTML={{ __html: this.props.body }}
      />

-     {this.props.postBodyComponents}
+     {process.env.NODE_ENV !== 'production' && this.props.postBodyComponents}

    </body>

This ensures you can still make use of gatsby's hot reload in development, but generated htmls will not include React & webpack generated scripts.

A more meticulous approach would be to loop over postBodyComponents & only removes the script tag that link to common.js , but for most case I think it'll be fine.


This definitely defeats the purpose of Gatsby, which has its own convention & complex process just so it can generate a progressive web app. For your case, if you're not already familiar with Gatsby, maybe it'd be simpler to roll your own SSR. My answer is only to show whether it's possible with Gatsby or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM