1

Is it possible in webpack.config.js to setup a module in a way that any needed css will automatically be loaded whenever the module is required?

So if I load bootstrap for example, also the needed css file(s) will be loaded by webpack without me having to type the extra require line myself everytime I require it.

Example:

require('bootstrap'); // This should load bootstrap.js as well as bootstrap.css

1 Answer 1

1

In order to require CSS in Webpack you need a specific loader (as with everything else). Once you add the loader, you just need to require it in each file you need. Webpack will automatically load it for you when need it, you just need to tell webpack to make a bundle out of it and require that bundle in your index/main html.

You are trying to require bootstrap js and css with the same require, I believe Webpack has no way of knowing you are trying to load two different files (even if common files). I believe you can do require('bootstrap) and require('bootstrap.css'), but I don't think you can load both in one step.

https://webpack.github.io/docs/stylesheets.html

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

5 Comments

I'm not asking how to require CSS in webpack, I'm asking how can I setup webpack to automatically load all needed CSS whenever I require a module. So when I require bootstrap, webpack will load the bootstrap JS file and the bootstrap CSS file from the single require('bootstrap') command?
Yes, my bad, understood the question awfully, I edited it
It was my fear it would be impossible for now... I remember RequireJS has an option to shim modules and from there state all dependencies for that module. I was hoping webpack had the same functionality..
Maybe I'm blind, but to be honest I don't even see a reason to do it. You save a few code lines, yes, but if that implies having Webpack checking more things and making it slower I don't think it's worth it. Webpack shines with it's speed and simpleness, I think having that feature collides with Webpack's motto
If there was some kind of dependency possibility you wouldn't have to take care of that in every file yourself, which would reduce the chances of errors. I don't think the speed would be a problem as it will only affect the bundling process

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.