vue配置px自动转rem

2022-07-28,,,

首先安装
npm install postcss-pxtorem --save-dev 或者 npm install postcss-pxtorem -D
npm install lib-flexible --save

然后在vue.config.js配置

module.exports = {
    css: {
        // 是否开启支持 foo.module.css 样式
        requireModuleExtension: true,
        // css预设器配置项
        loaderOptions: {
            css: {
                // options here will be passed to css-loader
            },
            postcss: {
                // options here will be passed to postcss-loader
                plugins: [
                    require('postcss-pxtorem')({
                        rootValue: 18.75, // 换算的基数
                        propList: ['*']
                    })
                ]
            }
        }
    }
}

然后新建rem.js文件

rem.js内容

//rem.js
// 设置 rem 函数
function setRem() {
    // 320 默认大小16px; 320px = 20rem ;每个元素px基础上/16
    const htmlWidth = document.documentElement.clientWidth || document.body.clientWidth
        // 得到html的Dom元素
    const htmlDom = document.getElementsByTagName('html')[0]
        // 设置根元素字体大小
    htmlDom.style.fontSize = htmlWidth / 20 + 'px'
}
// 初始化
setRem()
    // 改变窗口大小时重新设置 rem
window.onresize = function() {
    setRem()
}

最后在main.js中引用

import "../rem.js"

本文地址:https://blog.csdn.net/sslcsq/article/details/109364031

《vue配置px自动转rem.doc》

下载本文的Word格式文档,以方便收藏与打印。