微信小程序引入unocss

今天刚新建一个微信小程序,之前写过一篇《原子化CSS:Unocss的使用》,想着"偷懒"不想定义各种css样式类,于是准备把unocss引入进来使用。

安装与配置

1.安装依赖

复制代码
npm add -D unocss unocss-preset-weapp

2.配置unocss.config.ts

复制代码
import { defineConfig } from "unocss";
import presetWeapp from 'unocss-preset-weapp'
const include = [/\.wxml$/]

export default defineConfig({
  content:{
    pipeline:{
      include
    }
  },
  presets: [
    presetWeapp(),
  ],
  // 自定义规则
  rules: [],
  separators:'__'
})

3.在 package.json 中添加脚本命令,用于监听 wxml 文件并生成 wxss 文件:

复制代码
  "scripts": {
    "unocss": "unocss pages/**/*.wxml -c unocss.config.js --watch -o unocss.wxss"
  }

4.插入app.wxss中:

复制代码
@import '/unocss.wxss';

5.自定义组件中如果需要的话还得再配置一下,否则写了也不生效:

复制代码
Component({
  options: {
    addGlobalClass: true
  },
})

6.启动监听:

复制代码
npm run unocss

可能遇到的问题

1.单位换算不统一:

使用过程中会发现,对于width/height和padding/magin的单位换算是不一样的,比如:w-400和p-40:

关于这个问题,在github上的issues中也有人提到了:

https://github.com/MellowCo/unocss-preset-weapp/issues/123

https://github.com/MellowCo/unocss-preset-weapp/issues/116

当然在unocss-preset-weapp文档中也简略的说了如何解决这个问题:

因此只要在unocss.config.ts中定义rules进行覆盖就可以了,最终unocss.config.ts配置:

复制代码
import { defineConfig } from "unocss";
import presetWeapp from 'unocss-preset-weapp'
const include = [/\.wxml$/]

export default defineConfig({
  content:{
    pipeline:{
      include
    }
  },
  presets: [
    presetWeapp(),
  ],
  rules: [
    [/^p-(\d+)$/, ([, d]) => ({ padding: `${d}rpx` })],
    [/^pt-(\d+)$/, ([, d]) => ({ 'padding-top': `${d}rpx` })],
    [/^pb-(\d+)$/, ([, d]) => ({ 'padding-bottom': `${d}rpx` })],
    [/^pl-(\d+)$/, ([, d]) => ({ 'padding-left': `${d}rpx` })],
    [/^pr-(\d+)$/, ([, d]) => ({ 'padding-right': `${d}rpx` })],
    [/^m-(\d+)$/, ([, d]) => ({ margin: `${d}rpx` })],
    [/^mt-(\d+)$/, ([, d]) => ({ 'margin-top': `${d}rpx` })],
    [/^mb-(\d+)$/, ([, d]) => ({ 'margin-bottom': `${d}rpx` })],
    [/^ml-(\d+)$/, ([, d]) => ({ 'margin-left': `${d}rpx` })],
    [/^mr-(\d+)$/, ([, d]) => ({ 'margin-right': `${d}rpx` })] 
  ],
  separators:'__'
})

效果预览:

相关推荐
蜗牛前端2 天前
codex 全流程开发上线的高颜值礼簿小程序
前端·微信小程序
爱勇宝6 天前
我想认真做一件小事:让孩子和家长更好地互动
微信小程序·小程序·云开发
唯火锅不可辜负6 天前
避坑指南:iOS 下 scroll-view 嵌套 fixed 布局的“翻车”现场与修复
微信小程序
didiplus6 天前
运维人的随身神器:我把25个常用工具塞进了微信小程序
微信小程序
一份执念7 天前
uni-app 小程序分包限制处理与主包体积优化实战
前端·微信小程序
一份执念7 天前
ECharts 安装与使用完全指南:从全量引入到小程序分包优化
微信小程序·echarts
skiyee8 天前
🔥UniApp 仅需 5 行代码!实现所有页面中控制应用主题变化
前端·微信小程序
Jinkey9 天前
要用户手机号真的是为了打骚扰电话吗?浅谈微信生态会员账号体系与资产合并
后端·微信·微信小程序
用户43242810611411 天前
微信小程序从0到1接入微信支付的完整攻略
微信小程序
spmcor13 天前
微信小程序 setStorageSync 踩坑实录:别让"顺手一存"变成"隐形炸弹"
微信小程序