带有 less 和 postcss 自动前缀的 webpack

Posted

技术标签:

【中文标题】带有 less 和 postcss 自动前缀的 webpack【英文标题】:webpack with less and postcss autoprefixer 【发布时间】:2018-05-30 11:34:34 【问题描述】:

我是 webpack 的新手,我正在尝试将所有内容设置为在 react 项目上工作。我已经设法让 webpack 中的所有内容都按预期工作,但在使用 autoprefixer 时遇到了障碍。

我已经关注了 post css 和 autoprefixer 的文档,我显然在这里遗漏了一些重要的东西,或者做了一些愚蠢的事情。你能看看我的配置,如果你有任何建议,请告诉我。

其他 postcss 插件像 nanocss 一样运行良好。虽然我已经尝试过 cssnext,因为我认为它包括 autoprefixer。

我假设这是一个自动前缀配置问题。

如果您键入 npx autoprefixer info,另一件事是在命令行中。一切看起来都很好。当我构建或运行开发服务器时没有错误,它只是不会自动添加任何前缀。

这是我所有的配置文件。提前致谢。

.browserlistrc

# Browsers that we support

> 1%
Last 2 versions
IE 8 # sorry

webpack.config.js

const path = require('path');

const htmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');

// Constant with our paths
const paths = 
  DIST: path.resolve(__dirname, 'dist'),
  SRC: path.resolve(__dirname, 'src'),
  JS: path.resolve(__dirname, 'src/js'),
;

// Webpack configuration
module.exports = 
  entry: path.join(paths.JS, 'app.jsx'),
  output: 
    path: paths.DIST,
    filename: 'app.bundle.js',
  ,
  // Tell webpack to use html plugin and extract css to separate bundle
  plugins: [
    new HtmlWebpackPlugin(
      template: path.join(paths.SRC, 'index.html'),
    ),
    new ExtractTextPlugin('style.bundle.css'),
  ],
  // Loaders configuration
  module: 
    rules: [
      
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: [
          'babel-loader',
        ],
      ,
      
        test: /\.less$/,
        use: ExtractTextPlugin.extract(
          use: ['css-loader', 'postcss-loader', 'less-loader'],
        ),
      ,
      
        test: /\.(png|jpg|gif)$/,
        use: [
          'file-loader',
        ],
      ,
    ],
  ,
  resolve: 
    extensions: ['.js', '.jsx'],
  ,
;

postcss.config.js

module.exports = 
  plugins: [
    require('autoprefixer'),
    // require('cssnano')
  ]

我现在也尝试了 Laurent 的建议。我不确定这是否取得了进展,但我现在收到了一些错误记录。我的配置现在看起来像这样,没有 postcss.config

  const path = require("path");

    const HtmlWebpackPlugin = require("html-webpack-plugin");
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    const webpack = require("webpack");
    const autoprefixer = require("autoprefixer");

    // Constant with our paths
    const paths = 
      DIST: path.resolve(__dirname, "dist"),
      SRC: path.resolve(__dirname, "src"),
      JS: path.resolve(__dirname, "src/js")
    ;

    // Webpack configuration
    module.exports = 
      entry: path.join(paths.JS, "app.jsx"),
      output: 
        path: paths.DIST,
        filename: "app.bundle.js"
      ,
      // Tell webpack to use html plugin and extract css to separate bundle
      plugins: [
        new HtmlWebpackPlugin(
          template: path.join(paths.SRC, "index.html")
        ),
        new ExtractTextPlugin("style.bundle.css"),
        new webpack.ProvidePlugin(
          $: "jquery",
          jQuery: "jquery"
        )
      ],
      // Loaders configuration
      module: 
        rules: [
          
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: ["babel-loader"]
          ,
          
            test: /\.less$/,
            use: ExtractTextPlugin.extract(
              use: [
                "css-loader",
                
                  loader: "postcss-loader",
                  options: 
                    plugins: () =>
                      autoprefixer(
                        browsers: ["last 3 versions", "> 1%"]
                      )
                  
                ,
                "less-loader"
              ]
            )
          ,
          
            test: /\.(png|jpg|gif)$/,
            use: ["file-loader"]
          
        ]
      ,
      resolve: 
        extensions: [".js", ".jsx"]
      ,
      devtool: "source-map"
    ;

日志是这个

Project is running at http://localhost:8131/
webpack output is served from /
Hash: 546e87b727efc5c86ece
Version: webpack 3.10.0
Time: 2158ms
            Asset       Size  Chunks                    Chunk Names
    app.bundle.js    1.32 MB       0  [emitted]  [big]  main
app.bundle.js.map    1.59 MB       0  [emitted]         main
       index.html  297 bytes          [emitted]
   [4] ./node_modules/react/index.js 190 bytes 0 [built]
  [16] multi (webpack)-dev-server/client?http://localhost:8131 ./src/js/app.jsx 40 bytes 0 [built]
  [17] (webpack)-dev-server/client?http://localhost:8131 7.95 kB 0 [built]
  [18] ./node_modules/url/url.js 23.3 kB 0 [built]
  [25] ./node_modules/strip-ansi/index.js 161 bytes 0 [built]
  [27] ./node_modules/loglevel/lib/loglevel.js 7.86 kB 0 [built]
  [28] (webpack)-dev-server/client/socket.js 1.05 kB 0 [built]
  [30] (webpack)-dev-server/client/overlay.js 3.73 kB 0 [built]
  [35] (webpack)/hot nonrecursive ^\.\/log$ 170 bytes 0 [built]
  [36] (webpack)/hot/log.js 1.04 kB 0 [optional] [built]
  [37] (webpack)/hot/emitter.js 77 bytes 0 [built]
  [39] ./src/js/app.jsx 2.5 kB 0 [built]
  [43] ./node_modules/react-dom/index.js 1.36 kB 0 [built]
  [52] ./src/css/style.less 1.5 kB 0 [built] [failed] [1 error]
  [53] ./src/js/interface.js 384 bytes 0 [built]
    + 41 hidden modules

ERROR in ./src/css/style.less
Module build failed: ModuleBuildError: Module build failed: TypeError: css.walkAtRules is not a function
    at Processor.remove (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\autoprefixer\lib\processor.js:175:13)
    at Object.plugin (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\autoprefixer\lib\autoprefixer.js:87:32)
    at Object.parseOptions (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\postcss-loader\lib\options.js:5:37)
    at Promise.resolve.then (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\postcss-loader\lib\index.js:68:27)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
    at runLoaders (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\webpack\lib\NormalModule.js:195:19)
    at C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\loader-runner\lib\LoaderRunner.js:364:11
    at C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\loader-runner\lib\LoaderRunner.js:230:18
    at context.callback (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\loader-runner\lib\LoaderRunner.js:111:13)
    at Promise.resolve.then.then.catch (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\postcss-loader\lib\index.js:189:71)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./src/css/style.less
 @ ./src/js/app.jsx
 @ multi (webpack)-dev-server/client?http://localhost:8131 ./src/js/app.jsx
Child html-webpack-plugin for "index.html":
     1 asset
       [0] ./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html 615 bytes 0 [built]
       [1] ./node_modules/lodash/lodash.js 540 kB 0 [built]
       [2] (webpack)/buildin/global.js 509 bytes 0 [built]
       [3] (webpack)/buildin/module.js 517 bytes 0 [built]
Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js!node_modules/postcss-loader/lib/index.js??ref--1-2!node_modules/less-loader/dist/cjs.js!src/css/style.less:
       [0] ./node_modules/css-loader!./node_modules/postcss-loader/lib?!./node_modules/less-loader/dist/cjs.js!./src/css/style.less 718 bytes 0 [built] [failed] [1 error]

    ERROR in ./node_modules/css-loader!./node_modules/postcss-loader/lib?!./node_modules/less-loader/dist/cjs.js!./src/css/style.less
    Module build failed: TypeError: css.walkAtRules is not a function
        at Processor.remove (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\autoprefixer\lib\processor.js:175:13)
        at Object.plugin (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\autoprefixer\lib\autoprefixer.js:87:32)
        at Object.parseOptions (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\postcss-loader\lib\options.js:5:37)
        at Promise.resolve.then (C:\Users\Dan\Desktop\projects\WeatherReactProject\node_modules\postcss-loader\lib\index.js:68:27)
        at <anonymous>
        at process._tickCallback (internal/process/next_tick.js:188:7)
webpack: Failed to compile.

css.walkAtRules 不是一个函数似乎是我的麻烦的根源。从配置的角度来看,一切似乎都很好。它应该找到它。

有什么想法吗?

谢谢!

【问题讨论】:

【参考方案1】:

我在同样的问题上苦苦挣扎并找到了解决方案。我还经历了应用 autoprefixer 的过程,它不起作用并且也没有显示任何错误消息。

我不知道我的解决方案是否能解决您的问题,但让我们试一试。我尝试转译 scss 代码,这与转译较少代码的过程基本相同。

我既没有定义 postcss.config.js 也没有定义 .browserlistrc 文件。相反,在 webpack.config.js 中,我首先

const autoprefixer = require('autoprefixer');

然后,我在 webpack.config.js 中设置了以下配置(这里相当于 less):

module: 
  rules: [
    // ... other rules ... 
     
      test: /\.less$/,
      loader: ExtractTextPlugin.extract(['css-loader',
      
        loader: 'postcss-loader',
        options: 
          plugins: () => autoprefixer(
            browsers: ['last 3 versions', '> 1%']
          )
        
      , 'less-loader'])
    
  // ... other rules ...
  ]
, 
plugins: [
   // ... other plugins ...
   new ExtractTextPlugin(
    filename: '[name].css',
    allChunks: true,
  )
  // ... other plugins ...
]

据我从大量论坛中了解到的信息,加载程序的顺序是“css-loader”、“postcss-loader”和“less-loader”是至关重要的。在我的特殊情况下,如果没有该选项,它根本不起作用


  browsers: ['last 3 versions', '> 1%']
    

希望这会有所帮助...

【讨论】:

【参考方案2】:

我遇到了同样的问题,我已正确修复它,但在我的配置中,我使用了 PostCSSSCSS 样式。克隆并查看PostCSS configuration on Webpack,它是如此简单并且可以正常工作。我不会在这里写我的Webpack 配置,因为它很难阅读和使用。毫无疑问,我没有使用单独的 PostCSS 配置文件。只需在Webpack 配置文件中写入PostCSS 配置即可。我更喜欢将Webpack 的开发和生产版本分开。看看,如果有问题请询问。我很乐意回答。

【讨论】:

以上是关于带有 less 和 postcss 自动前缀的 webpack的主要内容,如果未能解决你的问题,请参考以下文章

webpack.config.js====CSS相关:::postcss-loader加载器,自动添加前缀

对postcss以及less和sass的研究

Rollup 和 Post CSS - 自动为 React className 属性添加前缀

如何结合gulp使用postcss

webpack4xpostcss-loader无法自动添加浏览器前缀问题

Postcss-loader 没有缩小 CSS 输出