Gatsby 何时将第三方库包含到客户端 js 包中?

When does Gatsby include a third party library into the client side js bundle?

在 Gatsby 中,我使用 commonmarkjs 从我的 CMS 解析降价内容并将其呈现为 HTML。这是代码:

import React, { ReactNode, Component } from 'react'
import { HtmlRenderer, Parser } from 'commonmark' // <- I import some commonmarkjs classes...

interface Props {
  markdown: string
}

export default class Text extends Component<Props> {
  parsedMarkdown: string

  constructor(props: Props) {
    super(props)
    const parser = new Parser()
    const renderer = new HtmlRenderer()
    this.parsedMarkdown = renderer.render(parser.parse(props.markdown)) // <- ...and use them here
  }

  render(): ReactNode {
    return (
      <div className="text">
        <div dangerouslySetInnerHTML={{ __html: this.parsedMarkdown }} />
      </div>
    )
  }
}

我 运行 构建任务,然后我用 source-map-explorer 分析输出。这是结果:

您可以看到commonmark 包含在我的包中。 为什么? 我认为 Gatsby 足够聪明,只使用 lib 构建实际模板而不将其包含在我的包中。

由于 React 会在客户端滋润您的组件,因此默认情况下,执行此操作所需的任何代码都将包含在您的 Webpack 包中。如果你想要 trim 一些脂肪,你可以 adjust the Webpack configuration to replace or omit certain libraries, but be aware that the response from the GraphQL query is exported as page-data.json (more info) 并且你将需要将它转换为下游(即在组件内部)客户端的库。

如果您想将 Markdown 转换为 HTML 然后使用 dangerouslySetInnerHTML 而无需在组件代码中包含 Markdown 解析器,您可以使用 createResolvers 在GraphQL 层,使准备好的字符串在您的 page-data.json 中可用,并消除对库客户端的需求。

这就是说,我发现使用像 markdown-to-jsx(5kb 缩小)这样的轻量级 JSX 感知 Markdown 解析器是一种更可取的方法,它允许更大的灵活性和客户端安全性(不使用 dangerouslySetInnerHTML).