Adding external javascript to document page in Docusaurus v2

Viewed 540

I'm building a component library of just HTML snippet and corresponding js/css and I'm using Docusaurus to document those compoents. I have a document page for each component. On the document page there is an example of each component. I'd like to make the components functional (click events, keyboard nav, etc.) so I have attached the component javascript via a plugin:

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',
            },
          },
        ],
      };
    },
  };
};

In my docusaurus.config.js I've added my plugin:

...

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

...

This successfully adds the stylesheet and javascript in the correct locations. However the javascript never executes. It appears that my component javascript fires before the documentation app loads.

What am I missing? What is the correct way to add external javascript to documentation pages?

EDIT: I'm using "@docusaurus/core": "2.0.0-beta.0",

1 Answers

You can embed your components in Live Code block Docusaurus V2.

You will need to install the package using npm or 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',
    },
  },
};

You can find detailed information about this process by using the link below.

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

It should be noted that this only works with react components.

Related