Skip to content
00:00:00
0

uniapp使用unocss兼容小程序

新建的 uniapp 项目直接安装 unocss 使用后编译成小程序后发现样式根本不生效,在微信开发者工具查看编译后的代码,发现小程序不支持 \ \: \[ \$ \. 等转义类名,也即不支持 unocss 编译后的类名。

查找之后发现了一个兼容该问题的库:unocss-applet,下载之后配置即可,代码如下:

import type { Preset, SourceCodeTransformer } from 'unocss';
import { defineConfig, presetAttributify } from 'unocss';

import {
  presetApplet,
  presetRemRpx,
  transformerAttributify,
} from 'unocss-applet';

const isApplet = process.env?.UNI_PLATFORM?.startsWith('mp-') ?? false;

const presets: Preset[] = [];
const transformers: SourceCodeTransformer[] = [];

if (isApplet) {
  presets.push(presetApplet());
  presets.push(presetRemRpx());
  transformers.push(transformerAttributify({ ignoreAttributes: ['block'] }));
} else {
  presets.push(presetApplet());
  presets.push(presetAttributify());
  presets.push(presetRemRpx({ mode: 'rpx2rem' }));
}

export default defineConfig({
  presets: [
    // ...
    ...presets,
  ],
  transformers: [
    // ...
    ...transformers,
  ],
});
最近更新