jsPlumb uses Docusaurus, a super handy static site generator, for various parts of our ecosystem, including our Documentation and also our recently released stand alone components product.
While developing the site for jsPlumb Components, we wanted to include a couple of pieces of information that would vary depending on whether we were running in development mode locally (ie docusaurus start
) or building for production. We looked into the various options available, all based on the dotenv
plugin for Webpack, but couldn't find what we were looking for: a solution that worked, with minimal manual intervention, in both development mode and when building for production.
So we ended up building our own plugin. This plugin reads values from a JSON file and makes them available to your site via the customFields
map in the Docusaurus siteConfig
.
note
When I say "Docusaurus" in this post I am talking about v2. I've not used v1.
#
Installationnpm i @jsplumb/docusaurus-plugin-env-loader-json
#
ConfigurationYou just have to add the plugin to the list of plugins in docusaurus.config.js
:
plugins:[ "@jsplumb/docusaurus-plugin-env-loader-json" ],
and then create an env.json
file in the Docusaurus project directory.
#
env.jsonYour environment variables should be keyed under a section that identifies the environment you are targetting - "development" when using docusaurus start
and "production" when running a build. The plugin reads the environment name from the environment variable NODE_ENV
.
{ "production":{ "SERVER_URL":"https://some.server.com/anEndpoint" }, "development":{ "SERVER_URL":"http://localhost:4200/anEndpoint" }}
#
Accessing valuesYou can access these values via the customFields
section of the Docusaurus site config:
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
export function MyApp {
const {siteConfig} = useDocusaurusContext(); const serverUrl = siteConfig.customFields.SERVER_URL
...
}
#
Changing the configuration file nameIf you want to specify some file other than env.json
in your project's root, you can do so by setting the sourceFile
option of the plugin:
plugins:[ [ "@jsplumb/docusaurus-plugin-env-loader-json", { "sourceFile":"path/to/aFile.json" } ] ],
This path should be specified relative to the project root. No leading slash is required.