vite how to px 2 rpx
chentianxin opened this issue · comments
请问 vite uniapp vue3 项目如何把 tailwindcss px 转换成 rpx
配置项如下
// postcss.config.cjs
const plugins = [
require('tailwindcss')(),
require('autoprefixer')(),
require('postcss-rem-to-responsive-pixel')({
// 32 意味着 1rem = 32rpx
rootValue: 32,
// 默认所有属性都转化
propList: ['*'],
// 转化的单位,可以变成 px / rpx
transformUnit: 'rpx'
})
]
module.exports = {
plugins
}
// tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
// 这里给出了一份 uni-app /taro 通用示例,具体要根据你自己项目的目录结构进行配置
// 不在 content 包括的文件内编写的 class,不会生成对应的工具类
content: ['./index.html', './src/**/*.{html,js,ts,jsx,tsx,vue}'],
theme: {
extend: {},
colors: {}
},
// 其他配置项
// ...
corePlugins: {
// 不需要 preflight,因为这主要是给 h5 的,如果你要同时开发小程序和 h5 端,你应该使用环境变量来控制它
preflight: false
}
}
// vite.config.ts
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from 'weapp-tailwindcss/vite'
import { plugins as postcssPlugins } from './postcss.config.cjs'
// https://vitejs.dev/config/
export default defineConfig({
build: {
// 开发阶段启用源码映射:https://uniapp.dcloud.net.cn/tutorial/migration-to-vue3.html#需主动开启-sourcemap
sourcemap: process.env.NODE_ENV === 'development'
},
plugins: [
uni(),
uvwt(),
vueJsx({
// options are passed on to @vue/babel-plugin-jsx
})
],
css: {
postcss: {
plugins: postcssPlugins
},
preprocessorOptions: {
scss: {
additionalData: '@use "@/styles/variables.scss" as *;'
}
}
}
})
这个也是通过配置 postcss 插件做到 px->rpx 的,这里我们使用目前这方面最流行的 taro 团队的 postcss-pxtransform 来做,你可以这样配置:
require('postcss-pxtransform')({
platform: 'weapp',
// https://taro-docs.jd.com/docs/size
// 根据你的设计稿宽度进行配置
// 可以传入一个 function
// designWidth (input) {
// if (input.file.replace(/\\+/g, '/').indexOf('@nutui/nutui-taro') > -1) {
// return 375
// }
// return 750
// },
designWidth: 750, // 375,
deviceRatio: {
640: 2.34 / 2,
// 此时应用到的规则,代表 1px = 1rpx
750: 1,
828: 1.81 / 2,
// 假如你把 designWidth 设置成 375 则使用这条规则 1px = 2rpx
375: 2 / 1
}
})
把它加到 postcss-rem-to-responsive-pixel
后面即可
感谢🙇