1

I swizzled a component in Docusaurus to customize a header/admonition that appears at the top of all pages in my documentation depending on some condition. In this case, the particular condition is an environment variable that is set by my build pipeline (GITHUB_REF). If I'm on master, the header should be invisible. If my branch is next, it should be visible.

I'd like the ability to define a "global flag" at build time that indicates whether or not that header should be rendered on the site. However, I'm very unfamiliar with Typescript and React so I'm not sure how to go about it.

The header is in a file src/theme/DocItem/Content/index.tsx:

import React from 'react';
import Content from '@theme-original/DocItem/Content';
import type ContentType from '@theme/DocItem/Content';
import type { WrapperProps } from '@docusaurus/types';
import Admonition from '@theme/Admonition';
import Link from '@docusaurus/Link';

type Props = WrapperProps<typeof ContentType>;

function NextBanner(): JSX.Element | null {
  const isNext = process.env.GITHUB_REF === 'refs/heads/next'
  if (isNext) {
    return (
      <div className="alert alert--warning margin-bottom--md">
        This is documentation is for an unreleased version!
      </div>
    )
  }

  return null;
}

export default function ContentWrapper(props: Props): JSX.Element {
  return (
    <>
      <NextBanner />
      <Content {...props} />
    </>
  );
}

In the code above, const isNext is not really valid because process is not accessible from here. But I left it there to show the intent.

What is the best way to go about this?

void.pointer
  • 24,859
  • 31
  • 132
  • 243

1 Answers1

2

If you are using Create React App, you can define an environment variable by creating .env file adding an entry such as REACT_APP_GLOBAL_FLAG. These will be picked up during build time and will be replaced into the code. Then within code you can consume this like:

<>
 ...some elements
 {process.env.REACT_APP_GLOBAL_FLAG==="true" && renderComponent()}
</>

You can refer here: https://create-react-app.dev/docs/adding-custom-environment-variables

For webpack, you can use DefinePlugin for Webpack.

In Plugins, webpack.config.js:

new webpack.DefinePlugin({
  GLOBAL_FLAG: JSON.stringify(true)
});

In TS file:

if (!GLOBAL_FLAG) {
  console.log('Debug info');
}

This will be replaced to

if (!true) {
  console.log('Debug info');
}

You can refer here: https://webpack.js.org/plugins/define-plugin/#usage

Furthermore you can also check: this discussion too.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mahesh
  • 513
  • 3
  • 12