vue配置rem适配(postcss-pxtorem和amfe-flexible)

移动端vue配置 REM 适配

Vant 中的样式默认使用px作为单位,如果需要使用rem单位,推荐使用以下两个工具:

  1. postcss-pxtorem 是一款 postcss 插件,用于将单位转化为 rem

  2. amfe-flexible 用于设置 rem 基准值

  3. 使用 amfe-flexible 动态设置 REM 基准值(html 标签的字体大小)

1、安装

`yarn add amfe-flexible`
	或
`npm i amfe-flexible`

2、然后在 main.js 中加载执行该模块

import 'amfe-flexible'

最后测试:在浏览器中切换不同的手机设备尺寸,观察 html 标签 font-size 的变化。

2、 使用 postcss-pxtorem 将 px 转为 rem

  1. 安装

    yarn add -D postcss-pxtorem

    npm install postcss-pxtorem -D
    -D 是 --save-dev 的简写

  2. 然后在项目根目录中创建 postcss.config.js 文件

module.exports = {
  plugins: {
    "postcss-pxtorem": {
      // 设计稿 375:37.5
      // 设计稿:750:75
      // Vant 是基于 375
      rootValue: 37.5,
      propList: ["*"]
    }
  }
}
  1. 配置完毕,重新启动服务

    最后测试:在浏览器中审查元素的样式查看是否已将 px 转换为 rem。

  2. 注意:

    1.只能转换单独的 .css|.less|.scss 之类的文件、.vue 文件中的 style 中的 px

    2.不能转换行内样式中的 px

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在vite.config.ts中适配postcss-pxtoremamfe-flexible,需要进行如下配置: 1. 安装依赖 首先,需要安装postcss-pxtoremamfe-flexible这两个库,可以使用npm或yarn进行安装: ``` npm install postcss-pxtorem amfe-flexible --save-dev ``` ``` yarn add postcss-pxtorem amfe-flexible --dev ``` 2. 配置vite.config.ts 在vite.config.ts中,需要添加一个postcss插件,并将amfe-flexible作为其参数传入,同时也需要配置postcss-pxtorem插件,代码如下: ```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import postcssPxToRem from 'postcss-pxtorem'; export default defineConfig({ plugins: [ vue(), { name: 'postcss', async transform(css, id) { if (id.endsWith('.vue') || id.endsWith('.css')) { const { default: postcss } = await import('postcss'); const { default: flexible } = await import('amfe-flexible'); const processor = postcss([postcssPxToRem({ rootValue: 37.5, propList: ['*'], })]); const result = await processor.process(css, { from: id }); return { code: result.css, map: result.map, }; } }, enforce: 'post', }, ], }); ``` 这里使用了vite的postcss插件,该插件可以通过调用postcss的API来处理CSS文件。在transform函数中,首先判断当前文件的类型是否为.vue或.css,然后使用postcss-pxtorempx转换成rem,其中rootValue为根元素的字体大小,propList为要转换的属性列表,这里设置为所有属性都转换。 同时,将amfe-flexible作为postcss插件的参数传入,这样就可以自适应不同屏幕尺寸。 需要注意的是,由于postcss插件是异步执行的,因此需要使用async/await来等待插件执行完成后再返回结果。 以上就是在vite.config.ts中适配postcss-pxtoremamfe-flexible的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值