aspirisen
aspirisen

Reputation: 1025

Webpack: How to compile all less files in a project

I use webpack for JS and now I want to use it for styles. I have a lot of styles in different folders and i want to compile them all without requiring each of them mannaully. The question is how to gather all the .less files in the folders and compile them via less-loader?

Upvotes: 3

Views: 2253

Answers (2)

aspirisen
aspirisen

Reputation: 1025

I found some workaround using require.context.

First you need to create a js file in the root of the styles folder if you don't have one.

Use this code if you use css or less and always extract them

require.context('./', true, /(\.less$)|(\.css$)/);

First argument is relative path to folder in which webpack should search for the files, second tells that it should search in subfolders and the last one is regexp of the extension of the files that webpack should require. Then you need to requre this file or use it as entry point. This works if you use extract-text-webpack-plugin but doesn't work otherwise.

Using styles without extracting them to style separate file

The example above doesn't work if you don't extract them because webpack generate modules with styles but doesn't execute them. This is complete example that works in both cases:

(function (requireContext) {
    return requireContext.keys().map(requireContext);
} (require.context('../', true, /(\.less$)|(\.css$)/)));

Upvotes: 4

Brendan Gannon
Brendan Gannon

Reputation: 2652

This isn't how webpack is meant to work, really. If you really want to do this, grunt/gulp is going to be a better choice.

Webpack's require mechanism ensures you build only the CSS you need for any given entry point, and gives you dependency management as well. If you do want to use webpack, but don't want to use the style-loader to insert them into the DOM etc., you can use the Extract Text plugin to build your compiled CSS into a separate file.

Upvotes: 3

Related Questions