1

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! Can you please give a reference - so that I can check the implementation.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.