Conditional Import based on environment variable

后端 未结 1 793
孤独总比滥情好
孤独总比滥情好 2020-12-17 22:05

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

相关标签:
1条回答
  • 2020-12-17 22:22

    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

    0 讨论(0)
提交回复
热议问题