I’m having a frustrating time getting my CSS to apply autoprefixing and minification correctly in my Webpack setup. Despite following various tutorials and adjusting my configuration, the resulting CSS does not seem to reflect the expected styles, and the autoprefixer does not seem to be working.
Here’s a breakdown of my project setup:
Project Structure:
/my-project
|-- /src
| |-- /js
| | |-- app.js
| |-- /styles
| | |-- app.scss
| |-- index.html
|-- package.json
|-- webpack.config.js
|-- postcss.config.js
package.json Dependencies:
{
"devDependencies": {
"autoprefixer": "^10.4.0",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.3.2",
"mini-css-extract-plugin": "^2.4.5",
"postcss-loader": "^6.2.1",
"postcss-preset-env": "^7.0.1",
"cssnano": "^5.0.7",
"sass-loader": "^12.1.0",
"webpack": "^5.59.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.0.0"
}
}
webpack.config.js:
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const glob = require("glob");
module.exports = (env, argv) => {
const isProduction = argv.mode === "production";
return {
entry: "./src/js/app.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "js/app.bundle.js",
clean: true,
},
module: {
rules: [
{
test: /.(s[ac]ss|css)$/i,
use: [
isProduction ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader",
"postcss-loader",
"sass-loader",
],
},
],
},
plugins: [
...glob.sync("./src/**/*.html").map((file) => {
return new HtmlWebpackPlugin({
template: file,
filename: path.basename(file),
});
}),
...(isProduction
? [
new MiniCssExtractPlugin({
filename: "css/[name].css",
}),
]
: []),
],
mode: isProduction ? "production" : "development",
};
};
postcss.config.js:
module.exports = {
plugins: [
require('postcss-preset-env')({
stage: 1,
}),
require('autoprefixer'),
require('cssnano')({
preset: 'default',
}),
],
};
CSS File (app.scss):
body {
display: flex;
align-items: center;
justify-content: center;
}
Issues Encountered:
The resulting CSS file does not include any prefixes for flexbox properties.
The CSS is not being minified as expected in production mode.
I’ve confirmed that all necessary packages are installed, and I’m running the commands correctly.
What I’ve Tried:
I ensured that all dependencies are up to date.
I simplified my Webpack configuration for testing.
I checked the output in both development and production modes.
I verified the structure of my SCSS and JavaScript files.
Additional Information:
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"dev": "webpack serve --mode development",
"build": "webpack --mode production"
},
Questions:
What might be causing the autoprefixer not to work as expected in my Webpack setup?
Are there any common pitfalls in configuring PostCSS with Webpack that I might be missing?
Any help or insights would be greatly appreciated!