【问题标题】:How best to include HTML with Gatsy site behind PrivateRoute?如何最好地在 PrivateRoute 后面包含带有 Gatsy 站点的 HTML?
【发布时间】:2020-03-06 19:57:17
【问题描述】:

我想将 Javadoc 生成的 HTML 代码放在 Gatsby 站点中,这样 HTML 只能通过经过身份验证的路由访问。

因此我的网站可能看起来像这样,使用reach/router 进行路由:

    <Layout>
        <Router>
            <PrivateRoute path={'/docs/api1'} component={MyApiDisplay}/>
            <PrivateRoute path={'/docs/api2'} component={MyApiDisplay}/>
            <NotFoundComponent default/>
        </Router>
    </Layout>

其中MyApiDisplay 是一些可以显示Javadoc 的组件,可能在IFrame 中。

将 HTML 包含到 Gatsby 网站的最佳方式是什么? docs 建议使用 static 文件夹来保存 HTML,但这是公开的,我不想要。

【问题讨论】:

标签: reactjs gatsby


【解决方案1】:
  1. 将您的 HTML 放在内容文件夹中:
root
 |--content
 |   `--javadoc
 |       `--generated.html
  1. 将 gatsby-source-filesystem 指向您的 html 文件夹:
// gatsby-config.js
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/content/javadoc`,
    name: `javadoc`,
  },
},
  1. gatsby-node.js 中,您可以使用loadNodeContent 来读取原始html。关注API 创建节点。
exports.onCreateNode = async ({
  node, loadNodeContent, actions
}) => {

  // only care about html file
  if (node.internal.type !== 'File' || node.internal.mediaType !== 'text/html') return;

  const { createNode } = actions;

  // read the raw html content
  const nodeContent = await loadNodeContent(node);

  // set up the new node
  const htmlNodeContent = {
    content: nodeContent,
    name: node.name, // take the file's name as identifier
    internal: {
      type: 'HTMLContent',
    }
    ...otherNecessaryMetaDataProps
  }

  createNode(htmlNode);
}
  1. 创建您的 template component 以查询并包含您的 HTML:
src/templates/blog-post.js

import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
export default ({ data }) => {
  const generated = allHtmlContent // Make sure to deconstruct your query result correctly
  return (
    <Layout>
      <div>

        {*/ #### Supply your HTML markup to this template here #### /*}

        <div dangerouslySetInnerHTML={{ __html: generated }} />
      </div>
    </Layout>
  )
}


/* #### Query your HTML here #### */

export const query = graphql`
{
  allHtmlContent {
    edges {
      node {
        name
        content
      }
    }
  }
}
`
  1. 将您的模板组件放置在您在问题中显示的私有路径中。

感谢@ksav 和question he linked


编辑

Javadoc 的输出不仅仅是 HTML,它包括 css、js 和图像。如果需要支持这些其他文件类型,您的答案有何变化?

css

确保您正确导入样式import "styles.css";,并将类名称设置为您在 html 和 css 中需要的名称。

javascript

blog 提供了几种可能性。这里的答案取决于您的实现。我为此推荐一个新问题。

图片

取决于您是使用绝对路径还是相对路径。绝对路径不需要更改。相对路径可能是个问题,因为 Gatsby 会移动您的文件。对于相对路径,我推荐一个新问题。

【讨论】:

  • Javadoc 的输出不仅仅是 HTML,它包括 css、js 和图像。如果需要支持这些其他文件类型,您的答案有何变化?
  • 恐怕这不适用于 HTML 页面中的链接。这是一个部分答案,只是正确地呈现了一个单独的 HTML 页面。很抱歉,但我不能接受当前措辞的这个答案,因为问题是指渲染网站(Javadoc 的输出,包括多种文件类型和页面之间的链接)。
猜你喜欢
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 2010-09-16
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多