Home > Software design >  How to import url in css file from environment variable
How to import url in css file from environment variable

Time:01-31

I have index.css file in React app and I am importing an external css file as below.

@import url('https://externalurldev01.blob.core.windows.net/XXX/index.css');

And this url will differ for different env.

Dev : @import url('https://externalurldev01.blob.core.windows.net/XXX/index.css');
QA : @import url('https://externalurltest01.blob.core.windows.net/XXX/index.css');
PROD : @import url('https://externalurlprod01.blob.core.windows.net/XXX/index.css');

How can I dynamically do the import based on env.

For now I have a workaround of creating three index.css as index-dev.css,index-qa.css,index-prod.css file and import it conditionally from the js file.

But I am looking for some solution so that I need not create three files. Rather get the env from environment variable. Something like below

@import url('https://externalurl" process.env.REACT_APP_ENV "01.blob.core.windows.net/XXX/index.css');

But the concatenation is not working.

CodePudding user response:

process.env is only available on the backend so you can not use it in css or js in browser. The way I usually do this is to populate the value on data-* attribute in html and then extract this attribute value in css using the attr() function or dataset property in js.

CodePudding user response:

I am able to solve the problem.

I am dynamically importing the css file as below.

    useEffect(() => {
      var head = document.head;
      var link = document.createElement("link");
  
      link.type = "text/css";
      link.rel = "stylesheet";
      link.href = window.REACT_APP_THEME;
  
      head.appendChild(link);
  
      return () => { head.removeChild(link); }
  
    }, []);

Since the app is deployed in Kubernetes cluster, so getting setting the window variable from the configmap.

  • Related