解决vue安装postcss-pxtorem相关报错

相信最近使用postcss-pxtorem + amfe-flexible移动端适配的同学会发现,安装完postcss-pxtorem并配置好vue.config.js后,会报错 Error: PostCSS plugin postcss-pxtorem requires PostCSS 8.,明明是按以往配置,怎么突然出错了...

实际上postcss-pxtorem已经步入6.0版本。
需要依赖于postcss8.0实现(具体项还没研究清楚~~TAT)

那么解决办法也很简单,查看package.jsonpostcss-pxtorem的版本是否在6.0以上。
如果是,通过$ npm install postcss -D把postcss安装了就行,其他一切如常。
因为自动安装最新,所以不用担心postcss不是8.0的。

或者你不想这么麻烦,可以选择使用postcss-pxtorem5.0的,通过命令$ npm install [email protected] -D安装就行,这样就不用添加postcss依赖了。


其他配置如下:

  • main.js中引用amfe-flexible

    import "amfe-flexible";
  • 根文件目录创建vue.config.js文件,添加如下配置:

    module.exports = {
      css: {
        loaderOptions: {
          postcss: {
            plugins: [
              require("postcss-pxtorem")({
                // 把px单位换算成rem单位
                rootValue: 37.5, // 换算的基数(设计图750的根字体为75)
                // selectorBlackList: ['weui', 'mu'], // 忽略转换正则匹配项
                propList: ["*"],
              }),
            ],
          },
        },
      },
    };

然后重新运行项目就可正常使用了。
不过只能转换css、sass、less等外部样式,以及vue文件中的style标签内的样式。
对于行内样式是没办法转换的。
在这里插入图片描述
解决vue安装postcss-pxtorem相关报错_第1张图片
在这里插入图片描述
在这里插入图片描述
html的font-size会随着设备宽度进行变化,就代表着已经设置成功了。
当然也可以更直观的看是否被转换为rem了。
在这里插入图片描述

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