Using autoprefixer with postcss in webpack 2.x

前端 未结 4 1422
误落风尘
误落风尘 2021-02-07 01:15

How to use autoprefixer with webpack 2.x.

Previously, it used to be something like this...

...

module: {
  loaders: [
     {
       test:          


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-07 01:58

    Current webpack.config.js for using autoprefixer and postcss with webpack 2.1.0-beta.27

    const webpack = require('webpack')
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const autoprefixer = require('autoprefixer')
    
    module.exports = {
      entry: './index.js',
      devtool: 'inline-source-map',
      output: { filename: 'bundle.js', publicPath: '' },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: [
              'style-loader',
              { loader: 'css-loader', options: { modules: true, importLoaders: 1 } },
              { loader: 'postcss-loader' },
            ]
          },
          {
            test: /\.js$/,
            use: [ { loader: 'babel-loader', options: { presets: ['es2015', 'react', 'stage-2'] } } ],
            exclude: /node_modules/,
          }
        ]
      },
      plugins: [
        new HtmlWebpackPlugin({ title: 'Example', template: './index.html' }),
        new webpack.LoaderOptionsPlugin({ options: { postcss: [ autoprefixer ] } })
      ],
    }
    

    Note: The LoaderOptionsPlugin is a 'polyfill' required in webpack =< 2.1.0-beta.24. I will update this answer when I work out the new syntax.

    Running it:

    Have the following relevant packages in package.json:

    "dependencies": {
      "autoprefixer": "^6.5.4",
      "babel-core": "^6.7.6",
      "babel-loader": "^6.2.4",
      "babel-preset-es2015": "^6.6.0",
      "babel-preset-react": "^6.5.0",
      "babel-preset-stage-2": "^6.5.0",
      "babel-register": "^6.7.2",
      "babel-runtime": "^6.6.1",
      "css-loader": "^0.26.1",
      "postcss-loader": "^1.2.1",
      "style-loader": "^0.13.1",
      "webpack": "2.1.0-beta.27",
      "webpack-dev-server": "2.1.0-beta.12"
    }
    

    And the following relevant script in package.json:

    "scripts": {
      "dev": "NODE_ENV=dev webpack-dev-server --port 3000 --inline --hot"
    },
    

    And run it with

    yarn install
    npm run dev
    

提交回复
热议问题