Search code examples
webpackwebpack-2

Setting a config value in webpack config and access it from react component


I am working on a project with different brands. I have one generic webpack.config.js and also different config files for each brand. Below is example of one brand.

webpack.config.brand1.js

const pageTemplates = require('./page.templates.brand1.js');
let config = require('../../webpack.config.js');

// Set entry point
config.entry.app = './scripts/brands/brand1.js';

// Load in page templates
config.plugins.push(...pageTemplates);

module.exports = config;

brand1.js

import $ from 'jquery';

import { LocationChecker } from '../common';

import '../../styles/brand1.scss';

$(() => {
    new LocationChecker();
});

What I need to have is a variable (with the value of brand's name. eg. brand1) which can be imported in react component. So that I can check the value and hide/show section depending on the brand name. I would like to set this variable on build-level and access it in my react component. How would you do that? Note: I'm using webpack 2


Solution

  • The easiest way to do this is probably with DefinePlugin, which, unlike its name might suggest, doesn't define a plugin but global constants:

    config.plugins.push(
      ...pageTemplates,
      new webpack.DefinePlugin({BRAND: JSON.stringify('brand1')})
    );
    

    (or add the plugin to each pageTemplates)

    Alternatively, if you don't want a global BRAND constant, you could create config/brand1/Config.js, config/brand2/Config.js, etc. outside your source directory and add the appropriate path with

    config.resolve.modules.push(path.resolve(__dirname, 'config/brand1'))
    

    Then you can just import Config.js to access brand-specific definitions.