Skip to content

Need Help Minimizing CSS within JavaScript Chunk #1593

Closed
@Domeanor

Description

Issue Description:

Recently, I upgraded my project from webpack 4 to webpack 5, along with updating css-loader from version 0.28.11 to 6.8.1. In webpack version 5, the minimize option was removed in favor of using MiniCssExtractPlugin, CssMinimizerPlugin, and HTMLWebpackPlugin to inject styles into the HTML file.

However, my use case involves building only a JavaScript file and then uploading it to a CDN. From this CDN, the JavaScript file is injected into another React app. In this scenario, I need the CSS to be minimized within the JavaScript chunk itself.

Despite spending several days on this, I haven't been able to find a solution.

webpack config

const path = require('path');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
	mode: 'production',
	entry: ['./src/index.js'],
	optimization: {
		splitChunks: false,
		minimize: true,
		minimizer: [
			// For webpack@5 you can use the ... syntax to extend existing minimizers
			'...',
			new CssMinimizerPlugin(),
		],
	},
	output: {
		path: path.resolve(__dirname, 'dist'),
		filename: 'bundle.js',
	},
	module: {
		rules: [
			{
				test: /\.(js|jsx)$/,
				exclude: /node_modules/,
				use: {
					loader: 'babel-loader',
				},
			},
			{
				test: /\.css$/,
				include: [path.resolve(__dirname, './src')],
				use: ['style-loader', 'css-loader', 'postcss-loader'],
			},
		],
	},
	resolve: {
		extensions: ['.js', '.jsx'],
	},
	devServer: {
		port: 9002,
	},
};

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import './styles.css';

const App = () => {
	return (
		<div className={`container containercss`}>
			<h1>Hello, React with Webpack!!!</h1>
		</div>
	);
};

ReactDOM.render(<App />, document.getElementById('root'));

styles.css

.containercss {
  color: red,
}

div {
  background-color: yellow;
}

versions

"webpack": "^5.0.0",
"webpack-cli": "^5.0.0",
"css-loader": "^4.0.0",
"css-minimizer-webpack-plugin": "6.0.0",
"style-loader": "~3.3.4",

I am getting this bundle.js file where white space isn't removed

Screenshot 2024-04-23 at 17 07 57

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions