Theming Semantic UI React in GatsbyJS
Edward J. SchwartzComputer Security Researcher2 min. read

Semantic UI comes with the ability to add themes, but this must be done at build time. Semantic UI is built using LESS, a CSS pre-processing system. LESS adds variables and other useful features to CSS.

Unfortunately, the gatsbyjs starter that I was using imported the Semantic UI as a pre-built CSS file, so there was no easy way to change the theming. This blog post is about how to fix that. Unfortunately, it's harder than it should be!

  1. The first step is to add LESS support to gatsbyjs.

    First, install the module: npm install --save gatsby-plugin-less less

    Then add the module into gatsby-config.js:

    module.exports = {
      ...
      plugins: [
        ...,
        `gatsby-plugin-less`,
        ...
      ]
      ...
    }
  2. The next step is to add the Semantic UI LESS files to your gatsbyjs app. You can actually do this by installing the semantic-ui-less npm package: npm install --save semantic-ui-less

  3. Next you actually need to add the theming configuration files to your project. You can copy these from node-modules/semantic-ui-less, specifically the theme.config.example file and the _site directory. Copy these files to src/semantic and rename theme.config.example to theme.config and _site to site. Since we're using the semantic-ui-less NPM package, we can change the line that imports theme.less to @import (multiple) "~semantic-ui-less/theme.less";. We also need to change the @siteFolder line to @siteFolder: '../../src/semantic/site'; so it uses our version of the site directory. Also, because of an annoying bug, you should add @fontPath : '../assets/fonts'; to the end of theme.config. Having fun yet?

  4. Gatsbyjs will use webpack to load semantic-ui-less. If we don't do anything,semantic-ui-less will use its own theme config files. Since we want to use our own, we add the following to gatsby-node.js to make it use our version instead:

    const path = require('path');
    
    exports.onCreateWebpackConfig = ({ actions }) => {
      actions.setWebpackConfig({
        resolve: {
          alias: {
            '../../theme.config$': path.join(__dirname, 'src/semantic/theme.config'),
          },
        },
      });
    };
  5. Find references to the precompiled version of semantic, and change them to reference the semantic-ui-less version. For me, this required changing import "../css/semantic.min.css"; in my Layout component to import "semantic-ui-less/semantic.less";.

  6. Now we can finally start to theme! Take a look at node_modules/semantic-ui-less/themes/default/site.variables, and pick something to modify. Let's change the font to Comic Sans. We can do that by writing @fontName: 'Comic Sans MS'; in src/semantic/site/globals/site.variables.

  7. Behold the splendor of your new font!

Powered with by Gatsby 5.0