基于环境变量的条件导入 [英] Conditional Import based on environment variable

查看:96
本文介绍了基于环境变量的条件导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个react组件,该组件具有X个选项,用于使用CSS模块导入要导入的样式表.

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.主题

process.env.THEME

我不能使用:

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

我可以使用:

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

但是.....

import/no-dynamic-require护航规则开始生效,说明它是不好的. https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-dynamic-require.md

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?

更新:

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;

推荐答案

例如,作为一种解决方法,在安装组件时,您可以尝试检查env变量,然后需要如下所示的特定css文件:

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');
         }
    }
}

将其兑现为承诺应该使用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(() => {
    //...
});

参考部分: ES6模块加载器

这篇关于基于环境变量的条件导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆