Skip to content

Using UnoCSS in applet(UniApp / Taro) to be compatible with unsupported syntax. 在小程序中使用UnoCSS,兼容不支持的语法。

License

Notifications You must be signed in to change notification settings

unocss-applet/unocss-applet

Repository files navigation

UnoCSS Applet

Using UnoCSS in applet(for UniApp and Taro) to be compatible with unsupported syntax.

NPM version

English | 简体中文

Presets and Plugins

Installation

npm i unocss-applet --save-dev # with npm
yarn add unocss-applet -D # with yarn
pnpm add unocss-applet -D # with pnpm

Usage

UnoCSS config

uno.config.ts
import type { Preset, SourceCodeTransformer } from 'unocss'
import { defineConfig } from 'unocss'

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

// uni-app
const isApplet = process.env?.UNI_PLATFORM?.startsWith('mp-') ?? false
// taro
// const isApplet = process.env.TARO_ENV !== 'h5' ?? 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,
  ],
})


For Platform

UniApp + Vue3 + Vite

vite.config.ts (UnoCSS v0.58 or below) / vite.config.mts (UnoCSS v0.59 or above)

import { defineConfig } from 'vite'
import uniModule from '@dcloudio/vite-plugin-uni'
import UnoCSS from 'unocss/vite'

// @ts-expect-error missing types
const Uni = uniModule.default || uniModule

export default defineConfig({
  plugins: [
    Uni(),
    UnoCSS(),
  ],
})

main.ts

import 'uno.css'


Taro v3.6 + Vue3 + Webpack5

config/index.js (UnoCSS v0.59 or above)

import { createSwcRegister, getModuleDefaultExport } from '@tarojs/helper'

export default async () => {
  createSwcRegister({
    only: [filePath => filePath.includes('@unocss')],
  })
  const UnoCSS = getModuleDefaultExport(await import('@unocss/webpack'))
  return {
    mini: {
      // ...
      webpackChain(chain, _webpack) {
        chain.plugin('unocss').use(UnoCSS())
      }
    },
    h5: {
      // ...
      webpackChain(chain) {
        chain.plugin('unocss').use(UnoCSS())
      }
    }
  }
}

config/index.js (UnoCSS v0.58 or below)

import UnoCSS from 'unocss/webpack'

const config = {
  mini: {
    // ...
    webpackChain(chain, _webpack) {
      chain.plugin('unocss').use(UnoCSS())
    },
  },
  h5: {
    // ...
    webpackChain(chain, _webpack) {
      chain.plugin('unocss').use(UnoCSS())
    },
  },
}

app.ts

import 'uno.css'


Example

Acknowledgement

License

MIT License © 2022-PRESENT Neil Lee and all contributors.