To prevent Webpack from creating separate .js files for SCSS entries, you can use the mini-css-extract-plugin
in combination with the css-loader
and sass-loader
to extract the CSS from your SCSS files and bundle them into a single CSS file.
Here's how you can do it:
Install Dependencies: First, make sure you have the necessary dependencies installed:
bashnpm install mini-css-extract-plugin css-loader sass-loader node-sass webpack --save-dev
Configure Webpack: Modify your Webpack configuration to use the
mini-css-extract-plugin
to extract CSS from SCSS files.javascriptconst MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports = { entry: './src/index.js', // Your entry point output: { filename: 'bundle.js', // Output filename for your JS bundle }, module: { rules: [ { test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, // Extract CSS to separate file 'css-loader', // Translates CSS into CommonJS modules 'sass-loader', // Compiles Sass to CSS ], }, ], }, plugins: [ new MiniCssExtractPlugin({ filename: 'styles.css', // Output filename for your CSS bundle }), ], };
Update Entry Points: Remove the SCSS entry point from your main JS entry file (e.g., index.js), as it's now being extracted to a separate CSS file.
HTML File: In your HTML file, include the CSS bundle (styles.css) using a link tag:
html<!DOCTYPE html> <html> <head> <title>My App</title> <link rel="stylesheet" href="styles.css"> </head> <body> <!-- Your app content --> </body> </html>
With this setup, when you run the webpack build, it will generate a single CSS file (styles.css) containing all the SCSS styles, and the JavaScript bundle (bundle.js) will no longer include the SCSS entries.
By using the mini-css-extract-plugin
, you achieve better performance and a cleaner separation of CSS and JS in your application. It's especially useful when working with larger projects where it's essential to optimize the loading of styles.