This article brings you relevant knowledge about javascript, which mainly introduces issues related to webpack extracting css into separate files, including css compatibility processing and css compression. Let’s take a look at it together, I hope it will be helpful to everyone.
[Related recommendations: javascript video tutorial, web front-end】
1. Install the plug-in and introduce it
npm install mini-css-extract-plugin -D const MiniCssExtractPlugin = require('mini-css-extract-plugin')
2. Configure the plug-in plugins
plugins: [ new HtmlWebpackPlugin({ template:'./src/index.html' }), new MiniCssExtractPlugin({ filename:'css/built.css'//对输出的文件进行重命名,默认为main.css }) ],
3. Modify the loader file
{ test:/.css$/, use:[ //取代css-loader,提取js中css成单独文件(注意) MiniCssExtractPlugin.loader, //将css文件整合到JS文件中 'css-loader', ] },
1. Install the plug-in
npm install postcss-loader postcss-preset-env -D
2. Configure postcss-loader in module and configure postcss-preset-env plug-in
{ test:/.css$/, use:[ //取代css-loader,提取js中css成单独文件 MiniCssExtractPlugin.loader, //将css文件整合到JS文件中 'css-loader', //css兼容性处理:postcss --> postcss-loader postcss-preset-env //帮postcss找到package.json中browserslist里面的配置,通过配置加载指定的css兼容性样式 { loader:'postcss-loader', options: { ident: 'postcss',//默认配置 plugins: () => [ require('postcss-preset-env')() ] } } ] },
3. Configure browserslist in package.json
"browserslist":{ "development":[ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ], "production":[ ">0.1%", "not dead", "not op_mini all" ] }
4. In order to make the development environment in browserslist in package.json effective, the environment needs to be configured in webpack.config.js, because the default is the production environment, and we need a development environment for development
const {resolve}=require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') //设置node.js环境变量,默认是生产环境,配置后为开发环境; process.env.NODE_ENV = 'development';
1. Install the plug-in and reference
npm install optimize-css-assets-webpack-plugin -D const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin')
2. Configure the plug-in in plugins
plugins: [ new HtmlWebpackPlugin({ template:'./src/index.html' }), new MiniCssExtractPlugin({ filename:'css/built.css'//对输出的文件进行重命名 }), //压缩css文件 new OptimizeCssAssetsWebpackPlugin() ],
[Related video tutorials recommended: vuejs introductory tutorial, Web Front End Introduction】
The above is the detailed content of Example parsing webpack to extract css into separate files (code attached). For more information, please follow other related articles on the PHP Chinese website!