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

效果预览:

相关推荐
h_65432101 天前
微信小程序点击按钮跳转链接并显示
微信小程序·小程序
银迢迢1 天前
微信小程序的开发及问题解决
微信小程序·小程序
liyinchi19881 天前
原生微信小程序 textarea组件placeholder无法换行的问题解决办法
微信小程序·小程序
前端极客探险家2 天前
微信小程序全解析:从入门到实战
微信小程序·小程序
h_65432102 天前
微信小程序van-dialog确认验证失败时阻止对话框的关闭
微信小程序·小程序
-曾牛2 天前
基于微信小程序的在线聊天功能实现:WebSocket通信实战
前端·后端·websocket·网络协议·微信小程序·小程序·notepad++
CN自由之翼2 天前
【微信小程序】webp资源上传失败
微信小程序·小程序
小新1103 天前
微信小程序学习之搜索框
学习·微信小程序·小程序
小新1103 天前
微信小程序之将轮播图设计为组件
微信小程序·小程序
不爱吃饭爱吃菜3 天前
uniapp微信小程序-长按按钮百度语音识别回显文字
前端·javascript·vue.js·百度·微信小程序·uni-app·语音识别