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__.

exports.onCreateWebpackConfig = (
{ stage, rules, loaders, plugins, actions },
) => {
plugins: [
__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.

import React from "react";
export default props => (
<aside>some sidebar content</aside>

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.