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

效果预览:

相关推荐
晓风伴月7 小时前
微信小程序:在ios中border边框显示不全
ios·微信小程序·小程序
新酱爱学习8 小时前
前端海报生成的几种方式:从 Canvas 到 Skyline
前端·javascript·微信小程序
军军君0112 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具三:后端项目基础框架搭建上
前端·vue.js·spring boot·面试·elementui·微信小程序·uni-app
两个月菜鸟12 小时前
微信小程序进度条cavans
微信小程序·小程序
從南走到北12 小时前
JAVA青企码协会模式系统源码支持微信公众号+微信小程序+H5+APP
java·微信·微信小程序·小程序·uni-app·微信公众平台
mg66815 小时前
微信小程序入门实例_____从零开始 开发一个每天记账的微信小程序
微信小程序·小程序
sanhuamao15 小时前
Taro+nestjs+mongodb实现健身记录微信小程序
微信小程序·taro·nestjs
转转技术团队20 小时前
微信小程序 Skyline 渲染引擎解析:如何突破 WebView 的性能天花板
微信小程序
拼图2092 天前
微信小程序——配置路径别名和省略后缀
微信小程序·小程序