Conditional Import based on environment variable
Asked Answered
I

1

16

I have a react component which has X options for a stylesheet to be imported which is using CSS Modules.

I ideally want to have a global environment variable fetched by using e.g.

process.env.THEME

I can't use:

import MyStyleSheet from `${process.env.THEME}/my.module.css`

I can use:

const MyStyleSheet = require(process.env.THEME/my.module.css);

however.....

import/no-dynamic-require eslint rule kicks off saying its bad. https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md

All the articles and posts I read say its not possible. Surely this is a common want but I can't for the life of me work out how to do it. Any ideas?


Update:

import React from 'react';

const Classes = import('./${process.env.theme}/Button.module.css');

const Button = () => (
  <button className={Classes.button}>My Themed Button</button>
);

export default Button;
Insufferable answered 4/6, 2018 at 21:19 Comment(0)
A
2

For example as a workaround when your component is mounting you can try check env variables and then require specific css file like below:

class App extends Component {
    componentWillMount() {
         if(process.env.CUSTOM_ENV_VAR === 'test') {
            require('styles1.css');
         } else {
            require('styles2.css');
         }
    }
}

Resolving it as a promise should do the trick with css modules:

if (process.env.CUSTOM_ENV_VAR === 'theme1') {
    import('./theme1.css').then(() => {
        // ...
    });
else (process.env.CUSTOM_ENV_VAR === 'theme2') {
    import('./theme2.css').then(() => {
        //...
    });
}

import(`./${process.env.CUSTOM_ENV_VAR}.css`).then(() => {
    //...
});

reference-part: ES6 Module Loader

Astyanax answered 5/6, 2018 at 8:47 Comment(4)
Only problem with this is it does not allow me to use CSS Modules.Insufferable
Resolving it as a promise should do the trick with css modules. I'll update answer.Astyanax
Sorry been unable to check this out until now, this always returns a promise rather than the value before load, so css modules never initiates the value on the template. Updated my code with a bit more code.Insufferable
This doesn't really work (any more?). Building using 'require' always includes all static files in the build, even though they are within conditionals bound to environment variables!Godart

© 2022 - 2025 — McMap. All rights reserved.