70 %
Chris Biscardi

Applying theme options using webpack's defineplugin

Sometimes as a Gatsby theme author you need to take a theme option and inject it into the bundle in an arbitrary location. Using web pack's DefinePlugin lets us do this using special tokens.

Let's say we want to add some feature flags to our application to control whether the application is built with a sidebar or not. We can accept the option in the theme and use it to set up a feature flag called __FLAG_SIDEBAR_ENABLED__.

gatsby-node.js
JS
exports.onCreateWebpackConfig = (
{ stage, rules, loaders, plugins, actions },
options
) => {
actions.setWebpackConfig({
plugins: [
plugins.define({
__FLAG_SIDEBAR_ENABLED__: options.enableSidebar
})
]
});
};

Wherever we use this flag, webpack will replace the value with a boolean literal, so we can use this to enable or disable features of our application.

src/components/layout.js
JS
import React from "react";
export default props => (
<div>
{__FLAG_SIDEBAR_ENABLED__ && (
<aside>some sidebar content</aside>
)}
<main>{props.children}</main>
</div>
);

Note that when using this pattern, it can also be useful to consider using a custom configuration node instead, as that will let you useStaticQuery to access specific information.