微信小程序引入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:'__'
})

效果预览:

相关推荐
Uyker2 小时前
从零开始制作小程序简单概述
前端·微信小程序·小程序
打小就很皮...8 小时前
HBuilder 发行Android(apk包)全流程指南
前端·javascript·微信小程序
前端缘梦20 小时前
微信小程序登录方案实践-从账号体系到用户信息存储
前端·微信小程序
coding随想1 天前
2025年小程序开发全解析:技术储备、行业趋势与实战案例
微信小程序
Nueuis1 天前
微信小程序前端面经
前端·微信小程序·小程序
轩1152 天前
实现仿中国婚博会微信小程序
微信小程序·小程序
知否技术2 天前
2025微信小程序开发实战教程(一)
前端·微信小程序
喝牛奶的小蜜蜂2 天前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发
2501_918941052 天前
旅游微信小程序制作指南
微信小程序·小程序·旅游
邹荣乐2 天前
微信小程序动态tabBar实现:基于自定义组件,灵活支持不同用户角色与超过5个tab自由组合
前端·微信小程序·uni-app