JavaScript webpacker 编译 sass 的时候部分样式编码失效!

darren · October 09, 2019 · Last by darren replied at October 09, 2019 · 5492 hits

在 xx.sass 文件中,z-index

position: fixed;
z-index: 10;
right: 0;

执行

rails webpacker:compile

在编译出来的 xx-random_hex_string.css 中

;position:fixed;z-index:1;right:0;

为什么 webpacker 编译样式会存在部分 css 编码失效? "webpack": "^3.12.0", "sass-loader": "^6.0.7", "style-loader": "^0.21.0", "node-sass": 4.9.2 目前经过调试排除一下几个可能:

  1. webpack 的 cache, 调整了以上几个 css 语句的顺序,编译出来的 css 文件顺序相应改变,因此排除 webpack 的 cache
  2. 可以肯定 node-sass 可以正常工作,node-sass 原来是一个 c 库,是 libsass, 以下是 node-sass 的版本信息 ```shell node-sass 4.9.2 (Wrapper) [JavaScript] libsass 3.5.4 (Sass Compiler) [C/C++]
使用node-sass 命令


```shell
node-sass xx.scss xx.css --output-style=compressed

输出的 xx.css 文件中包含

;position:fixed;z-index:10;right:0;

这说明 libsass 应该是正常工作的

求大佬给出解决思路,或者 webpack 应该怎么调试?

终于在@rails/webpacker/packages/enviorments/production.js 找到了原因

module.exports = class extends Base {
  constructor() {
    super()

    this.plugins.append(
      'Compression',
      new CompressionPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        cache: true,
        test: /\.(js|css|html|json|ico|svg|eot|otf|ttf|map)$/
      })
    )

    this.plugins.append(
      'OptimizeCSSAssets',
      new OptimizeCSSAssetsPlugin({
        parser: safePostCssParser,
        map: {
          inline: false,
          annotation: true
        }
      })
    )

    this.config.merge({
      devtool: 'source-map',
      stats: 'normal',
      bail: true,
      optimization: {
        minimizer: [
          new TerserPlugin({
            parallel: true,
            cache: true,
            sourceMap: true,
            terserOptions: {
              parse: {
                // Let terser parse ecma 8 code but always output
                // ES5 compliant code for older browsers
                ecma: 8
              },
              compress: {
                ecma: 5,
                warnings: false,
                comparisons: false
              },
              mangle: {
                safari10: true
              },
              output: {
                ecma: 5,
                comments: false,
                ascii_only: true
              }
            }
          })
        ]
      }
    })
  }
}

注释掉这个插件即可

// this.plugins.append(
//   'OptimizeCSSAssets',
//   new OptimizeCSSAssetsPlugin({
//     parser: safePostCssParser,
//     map: {
//       inline: false,
//       annotation: true
//     }
//   })
// )
You need to Sign in before reply, if you don't have an account, please Sign up first.