webpack css file compilation, automatic prefixing, stripping

1 .css file compilation

By default, webpack can only compile js files, and the introduction of css requires loader support

// css file is written in js 
npm i style-loader - D
 // css file loader 
npm i css-loader - D

Add to the rules of webpack.config.js

{
    test: /\.css$/,
    use:['style-loader', 'css-loader']
}

2 .css automatically adds a prefix

// postcss-loader can automatically add -webkit -ms prefix to css 
npm i postcss-loader - D

// autoprefixer plugin, set 
npm i autoprefixer for browser compatibility - D

// Increase the option of postcss-loader to add a 
new file postcss.config.js, content:
module.exports = {
    plugins: {
        autoprefix: {
            browsers: ['last 7 iOS versions', 'last 3 versions', '> 1%']
        }
    }
}

3 .css stripping

// Install the stripping plugin (if you are a global webpack, you will be asked to install it to the current project when using it) 
npm i mini-css-extract-plugin - D

Introduced and used in webpack.config.js

// Introduce 
const MiniCssExtractPlugin = require("mini-css-extract-plugin" );
 // Add to plugins array 
plugins:[
     new MiniCssExtractPlugin({
        filename: "css/main.css",
    })
]
// Write the processing loader in the rules (the previous style-loader is removed, because there is no need to write the js file) 
rules:[
    {
        test: /\.css$/,
        use:[MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
    }
]

package.json file:

{
  "name": "csschange",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --config webpack.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^9.6.1",
    "css-loader": "^3.2.0",
    "mini-css-extract-plugin": "^0.8.0",
    "postcss-loader": "^3.0.0",
    "style-loader": "^1.0.0",
    "webpack": "^4.41.0",
    "webpack-cli": "^3.3.9"
  }
}

webpack.config.js file:

const path = require('path')
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
    entry:'./main.js',
    output:{
        filename:'bundle.js',
        path:path.resolve(__dirname,'./dist')
    },
    module:{
        rules:[
            {
                test: /\.css$/,
                use:[MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
            }
        ]
    },
    plugins:[
        new MiniCssExtractPlugin({
            filename: "css/main.css",
        })
    ]
}

postcss.config.js file:

module.exports = {
    plugins: {
        autoprefix: {
            browsers: ['last 7 iOS versions', 'last 3 versions', '> 1%']
        }
    }
}

 

Reprinted in: https://www.cnblogs.com/superjsman/p/11599662.html

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326568817&siteId=291194637