How to integrate postcss and webpack
source link: https://dev.to/ynwd/how-to-integrate-postcss-and-webpack-ed5
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Posted on Oct 16
How to integrate postcss and webpack
.
├── package.json
├── postcss.config.js
├── src
│ ├── autocomplete.css
│ ├── base.css
│ ├── index.js
│ └── main.css
└── webpack.config.js
Source code: https://github.com/ynwd/postcss
Create app dir
mkdir postcss && cd postcss
Init package:
npm init -y
Install postcss
npm i -D postcss postcss-cli
Create css file
/* src/main.css */
@import './base.css';
@import './autocomplete.css';
/* src/base.css */
html {
color: blue;
}
select {
appearance: none;
}
/* src/autocomplete.css */
.autocomplete {
color: #777;
}
Run postcss cli
run this to see the available commands
npx postcss --help
compile our existing css files
npx postcss src/main.css
You will see error messages:
You did not set any plugins, parser, or stringifier. Right now, PostCSS does nothing. Pick plugins for your case on https://www.postcss.parts/ and use them in postcss.config.js.
PostCSS plugins
Install postcss plugin
npm i postcss-import autoprefixer cssnano -D
-
postcss-import
is used to replace@import
with actual code. -
autoprefixer
is used to parse CSS and add vendor prefixes to CSS rules using values from Can I Use. It is recommended by Google and used in Twitter and Alibaba. -
cssnano
is used to ensure that the final result is as small as possible for a production environment.
Create postcss config
module.exports = {
plugins: [
require('postcss-import'),
require('autoprefixer'),
require('cssnano')({
preset: 'default',
}),
],
};
Compile
npx postcss src/main.css
It will print
html{color:blue}select{-webkit-appearance:none;-moz-appearance:none;appearance:none}.autocomplete{color:#777}
Add --dist dist
to write the out put to the file dist
folder
npx postcss src/main.css --dir dist
Webpack integration
Install webpack
npm i webpack webpack-cli -D
Install webpack loader
npm i css-loader mini-css-extract-plugin postcss-loader -D
Create webpack config
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module.exports = {
mode: "production",
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"postcss-loader",
],
},
],
},
plugins: [
new MiniCssExtractPlugin(),
],
}
create entry point
/* src/index.js */
import "./main.css";
compile
npx webpack
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK