微信小程序引入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 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround4 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround4 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
码云数智-大飞4 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54594 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序
Slow菜鸟4 天前
微信小程序开发(二)目录结构完全指南
微信小程序·小程序
攀登的牵牛花4 天前
给女朋友写了个轻断食小程序:去老丈人家也是先动筷了
前端·微信小程序
前端小雪的博客.4 天前
【保姆级教程】uniAI 插件高效开发 uni-app 微信小程序(附实战案例)
微信小程序·uni-app·ai编程·uniai
一叶星殇4 天前
微信小程序请求拦截器踩坑:避免重复刷新 token
微信小程序·小程序
笨笨狗吞噬者5 天前
【uniapp】小程序端解决分包的uni_modules打包后产物进入主包中的问题
前端·微信小程序·uni-app