在Docusaurus v2中将外部JavaScript添加到文档页面

3

我正在构建一个仅包含HTML代码片段及其对应的js/css的组件库,并使用Docusaurus来记录这些组件。我为每个组件创建了一个文档页面,在文档页面上有每个组件的示例。我想使这些组件具有功能性(点击事件、键盘导航等),因此我通过插件附加了组件的javascript:

module.exports = function (context, options) {
  return {
    name: 'docusaurus-plugin-component-assets',
    injectHtmlTags() {
      return {
        headTags: [
          {
            tagName: 'link',
            attributes: {
              rel: 'stylesheet',
              href: 'https://example.com/css/component.min.css',
            },
          },
        ],
        postBodyTags: [
          {
            tagName: 'script',
            attributes: {
              src: 'https://example.com/js/component.min.js',
            },
          },
        ],
      };
    },
  };
};

在我的 docusaurus.config.js 文件中,我添加了我的插件:
...

plugins: [
  'docusaurus-plugin-sass',
  path.resolve(__dirname, 'src/plugins/docusaurus-plugin-component-assets.js')
],

...

这样做可以成功添加样式表和javascript到正确的位置。但是javascript从未执行过。看起来我的组件javascript在文档应用程序加载之前就被触发了。

我漏掉了什么?向文档页面添加外部javascript的正确方法是什么?

编辑:我正在使用"@docusaurus/core": "2.0.0-beta.0"。

2个回答

3

我之前也遇到过这个问题(在Docusaurus v2上)。最终,我理解了客户端模块文档的意思,并执行了以下操作,这对我来说既适用于初始页面加载,也适用于导航事件后加载的页面。(由于这是一个单页应用程序,当您只是在文档中浏览时,它不是完整的页面加载,因此我必须单独处理该情况。)

  1. plugins/my-script.js(或任何你想要的名称)中创建一个新文件。
  2. docusaurus.config.js中的配置中添加clientModules: [require.resolve('./plugins/my-script')],
  3. 将类似以下代码插入到新文件中:
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';

const doYourCustomStuff = () => {
  // your JS code goes here
}

export function onRouteDidUpdate({location, previousLocation}) {
  // Don't execute if we are still on the same page; the lifecycle may be fired
  // because the hash changes (e.g. when navigating between headings)
  if (location.pathname === previousLocation?.pathname) return;
  doYourCustomStuff();
}

if (ExecutionEnvironment.canUseDOM) {
  // We also need to setCodeRevealTriggers when the page first loads; otherwise,
  // after reloading the page, these triggers will not be set until the user
  // navigates somewhere.
  window.addEventListener('load', () => {
    setTimeout(doYourCustomStuff, 1000);
  });
}

将您的JS代码放在给定的函数中。

注意:当从yarn start开发环境进行热加载更改时,您的效果仍然会中断。在这种情况下,不太痛苦的解决方法是手动重新加载。


-2
你可以在 Docusaurus V2 的实时代码块中嵌入组件。
你需要使用 npm 或 yarn 安装该包。
npm install --save @docusaurus/theme-live-codeblock

module.exports = {
  plugins: ['@docusaurus/theme-live-codeblock'],
  themeConfig: {
    liveCodeBlock: {
      /**
       * The position of the live playground, above or under the editor
       * Possible values: "top" | "bottom"
       */
      playgroundPosition: 'bottom',
    },
  },
};

您可以通过下面的链接找到有关此过程的详细信息。

https://docusaurus.io/docs/markdown-features/code-blocks#interactive-code-editor

需要注意的是,这仅适用于React组件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接