nuxt3-postcss-pxtorem rem适配踩坑

nuxt3使用postcss-pxtorem

安装相关包

npm i autoprefixer postcss postcss-pxtorem
// npm
"autoprefixer": "^10.4.2",
"postcss": "^8.4.5",
"postcss-pxtorem": "^6.0.0"

nuxt.config.js中修改配置

// nuxt.config.js
build: {
  postcss: {
    postcssOptions: require('./postcss.config.js'),
  },
},

新建postcss.config.js添加配置

// 新建postcss.config.js
module.exports = {
  plugins: {
    autoprefixer: {
      overrideBrowserslist: [
        "Android 4.1",
        "iOS 7.1",
        "Chrome > 31",
        "ff > 31",
        "ie >= 8",
        "last 10 versions", // 所有主流浏览器最近10版本用
      ],
      grid: true,
    },
    "postcss-pxtorem": {
      rootValue: 100,
      propList: ["*"],
    },
  },
}

在app.vue或者合适位置中添加该段rem脚本

  • 确保windwo,document存在
  • 尝试过各种ssr:false的方法还是不起效果,只能相当当期方法
<script setup lang='ts'>
function flexible (window, document) {
    var docEl = document.documentElement
    var dpr = window.devicePixelRatio || 1
  
    // adjust body font size
    function setBodyFontSize () {
      if (document.body) {
        document.body.style.fontSize = (12 * dpr) + 'px'
      }
      else {
        document.addEventListener('DOMContentLoaded', setBodyFontSize)
      }
    }
    setBodyFontSize();
  
    // set 1rem = viewWidth / 10
    function setRemUnit () {
      var rem = docEl.clientWidth / 10
      docEl.style.fontSize = rem + 'px'
    }
  
    setRemUnit()
  
    // reset rem unit on page resize
    window.addEventListener('resize', setRemUnit)
    window.addEventListener('pageshow', function (e) {
      if (e.persisted) {
        setRemUnit()
      }
    })
  
    // detect 0.5px supports
    if (dpr >= 2) {
      var fakeBody = document.createElement('body')
      var testElement = document.createElement('div')
      testElement.style.border = '.5px solid transparent'
      fakeBody.appendChild(testElement)
      docEl.appendChild(fakeBody)
      if (testElement.offsetHeight === 1) {
        docEl.classList.add('hairlines')
      }
      docEl.removeChild(fakeBody)
    }
  }
flexible(window, document)

你可能感兴趣的:(postcss,javascript,前端,vue)