记一次webpack配置postcss-loader下的autoprefixer无效的情况

按官方文档配置如下,发现并不能起作用。

Webpack

In webpack you can use postcss-loader with autoprefixer and other PostCSS plugins.

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader", "postcss-loader"]
      }
    ]
  }
}
And create a postcss.config.js with:

module.exports = {
  plugins: [
    require('autoprefixer')
  ]
}

到处查阅,经验证

发现需要package.json中配置browserlist,代码如下

package.json

{
  "name": "webpackdemo",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "scripts": {
    "start": "webpack"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^9.6.1",
    "css-loader": "^3.2.0",
    "file-loader": "^4.2.0",
    "node-sass": "^4.12.0",
    "postcss-loader": "^3.0.0",
    "sass-loader": "^7.2.0",
    "style-loader": "^1.0.0",
    "url-loader": "^2.1.0",
    "webpack": "^4.39.1",
    "webpack-cli": "^3.3.6"
  },
  "dependencies": {},
// 注意这里的browserslist
  "browserslist": [
    "last 2 versions",
    "> 1%",
    "iOS 7",
    "last 3 iOS versions"
  ]
}

webpack.config.js

const path = require('path')
console.log(path.resolve(__dirname, 'boundle'))
module.exports = {
    mode: 'development',
    entry: {
        main: './src/index.js'
    },
    module: {
        rules: [{
            test: /\.(jpg|png|gif)$/,
            use: {
                loader: 'url-loader',
                options: {
                    name: '[name]_[hash].[ext]',
                    outputPath: 'images/',
                    limit: 2048
                  }
            }
        },{
            test: /\.(scss)$/,
            use: [
                'style-loader', 
                { loader: 'css-loader', options: { importLoaders: 2 } }, 
                'sass-loader', 
                // 这里配置autoprefixer结合package.json中的browserlist这样就成功了
                {
                    loader: 'postcss-loader',
                    options:{
                        plugins: [require('autoprefixer')], 

                    }
                }]
        }]
    },
    output: {
        filename: 'boundle.js',
        path: path.resolve(__dirname, 'dist')
    }
}

 

你可能感兴趣的:(前端)