2

I am trying to conditionally require css for my react project and it works locally. However, when the react-scripts build command is executed by react js all css files get bundled into one and the conditional import no longer works.

if(isSmartPhoneOrTablet()){
    require("./mobileStyle.css");
}else {
    require("./style.css");
}

"build": "react-scripts build"

9
  • Well that's literally just an if/else statement, so there's no way it can satisfy both conditions if just run once. Either that snippet is being run multiple times (and the condition outcome is changing), or the issue is somewhere else. Can you provide some relevant, basic info about the build configuration/process? Commented Jun 19, 2018 at 4:02
  • Sure, the npm run build command puts all the css into one file that the server uses. It does not seem to understand that some imports are conditional. In practice only one condition is executed (of course), but the problem occurs in the npm run build command which puts all the css into one file. Commented Jun 19, 2018 at 4:13
  • I'm....confused. How are you building (webpack?). And where are you doing this conditional importing? Is it within a component, or within your build script somewhere? Also, can you add the relevant code from your build script doing the CSS stuff. Commented Jun 19, 2018 at 4:27
  • The conditional importing is in all of my components (they each have their own css file). I added the build script above and I am not sure how I am building with webpack. I have not written any code to do with webpack. Commented Jun 19, 2018 at 4:35
  • Ok well then you won't be able to import from specific CSS files if those files don't exist after the app is built. They'd need to be kept separate rather than all combined into one big file. I'm not familiar with Heroku, but do you have access to that build script in the package.json? Or wherever it's combining the CSS into a single file? Commented Jun 19, 2018 at 4:44

1 Answer 1

1

You could try something like

var cssfile;
if(isSmartPhoneOrTablet()){
    cssfile = "./mobileStyle.css";
}else {
    cssfile = "./style.css";
}
require(cssfile);
Sign up to request clarification or add additional context in comments.

2 Comments

@petermir Did this work for you? You have marked it as a correct answer.
No I use,if (isMobileOrTablet()) { module.exports = require("./mobileStyle.css"); } else { module.exports = require("./style.css"); }, but I had to change my build script to use webpack and create my own webpack configuration

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.