I want to bundle multiple scss and js entries into multiple output files using webpack.
I have tried different solutions for it, but non of them did what I needed.
This is how the directory structure looks like:
assets
package.json
webpack.config.js
css
dist
src
lib
pages
fonts.scss
main.scss
js
dist
lib
src
components
pages
App.js
I want to end up having the main.scss & all the scss files from the “css/src/pages” directory compiled to “css/dist/main.css” and “css/dist/pages/page-name.css”.
My webpack.config.js file looks like this:
const path = require('path');
const fs = require('fs');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
let config = {
mode: "production",
watch: true,
module: {
rules: [
{
test: /.scss$/i,
include: [
path.resolve(__dirname, 'css/src'),
path.resolve(__dirname, 'css/src/pages')
],
// use: [MiniCssExtractPlugin.loader, "css-loader", 'sass-loader']
// use: ['file-loader', 'sass-loader', 'css-loader']
use: [
{
loader : 'file-loader',
options: { outputPath: '/', name: '[name].css'}
},
'sass-loader'
]
}
]
},
// plugins: [new MiniCssExtractPlugin()],
// optimization: {
// minimize: true,
// minimizer: [new CssMinimizerPlugin()]
// }
};
const main = Object.assign({}, config, {
name: 'main',
entry: './js/src/App.js',
output: {
filename: 'app.min.js',
path: path.resolve(__dirname, 'js/dist'),
}
});
const exp = [main];
const jsDir = __dirname + "\js\src\pages";
const jsFiles = fs.readdirSync(jsDir);
jsFiles.forEach(fileName => {
const nameOnly = fileName.replace(".js", "");
const current = Object.assign({}, config, {
name: nameOnly,
entry: './js/src/pages/'+fileName,
output: {
filename: fileName,
path: path.resolve(__dirname, 'js/dist/pages'),
}
});
exp.push(current);
});
// const cssMain = Object.assign({}, config, {
// name: 'mainCss',
// entry: './css/src/main.scss',
// output: {
// filename: 'main.css',
// path: path.resolve(__dirname, 'css/dist'),
// }
// });
// exp.push(cssMain);
const cssDir = __dirname + "\css\src\pages";
const cssFiles = fs.readdirSync(cssDir);
cssFiles.forEach(fileName => {
const nameOnly = fileName.replace(".scss", "");
const current = Object.assign({}, config, {
name: nameOnly + "Css",
entry: './css/src/pages/'+fileName,
output: {
filename: nameOnly + ".css",
path: path.resolve(__dirname, 'css/dist/pages'),
}
});
exp.push(current);
});
module.exports = exp;
As you can see there are few lines that are commented out, those are part of the things I’ve tried, but non of it worked, unfortunately.
The scss files from the “css/src/pages” directory always print javascript inside like in the attached screenshot and the main.scss file is compiled well into css but not into the right directory (it goes to “css/dist/pages” too).

FYI – the javascript compilation works as expected.
Any help will be highly appreciated! Thank you in advance 🙂