项目简介
这是一个基于 Vite 和 UnoCSS 的 Naive UI 多主题切换插件库,旨在帮助开发者轻松实现 Naive UI 的多主题切换功能。
项目的主要特性和功能
- 多主题支持:支持多种主题配置,可轻松实现主题的切换。
- 虚拟模块:提供虚拟模块
~naive-ui-themes
,包含主题配置对象数组themes
和主题切换 hookuseTheme
。 - 自动收集配置:自动收集主题配置文件,将配置对象解码成 CSS 变量并挂载到指定元素上,同时收集文件名作为 UnoCSS 的 variants。
- 类型定义:生成主题配置文件的类型定义,辅助开发。
- HMR 支持:当主题配置文件发生变化时,自动更新虚拟模块。
安装使用步骤
安装
假设用户已下载项目源码文件,在项目中使用 pnpm
安装插件:
bash
pnpm add @bluryar/naive-ui-themes
配置
Unocss 预设
在 ./unocss.config.ts
中进行如下配置:
```ts
import { resolve } from 'node:path';
import { defineConfig, presetUno } from 'unocss';
import type { UserConfig } from 'unocss';
import { type FileReaderOptions, presetNaiveThemes, tryRemoveThemeVariant } from '@bluryar/naive-ui-themes';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
export const fileReaderOptions = { dir: resolve(__dirname, './src/themes'), patterns: ['*.(light|dark).(json|js|ts|cjs|mjs)'], } satisfies FileReaderOptions;
const config = { presets: [ tryRemoveThemeVariant(presetUno()), presetNaiveThemes({ ...fileReaderOptions, autoimportThemes:!!1, }), ], } satisfies UserConfig;
export default defineConfig(config); ```
Vite 插件
在 vite.config.ts
中进行如下配置:
```ts
import { defineConfig } from 'vite';
import UnoVitePlugin from '@unocss/vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import { naiveMultiTheme, unsafeFileReaderSync } from '@bluryar/naive-ui-themes';
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers';
import { fileReaderOptions } from './unocss.config';
// https://vitejs.dev/config/ export default defineConfig(() => { const { files } = unsafeFileReaderSync({...fileReaderOptions, parse:!!0 });
return { optimizeDeps: { include: ['vue', 'vue-router', 'pinia', 'lodash', 'lodash-es'], }, plugins: [ vue(), vueJsx(), UnoVitePlugin({ configDeps: [...files], }), naiveMultiTheme({ dts: './src/types/auto-naive-theme.d.ts', ...fileReaderOptions, }), ], }; }); ```
使用
编写主题
在 src/default.dark.json
中编写主题配置:
jsonc
{
"common": {
"primaryColor": "#409eff"
//...
// 这部分配置可以使用 naive-ui 的 文档提供的主题配置器来配置
}
}
激活主题配置
在 src/App.vue
中激活主题配置:
```vue
```
切换主题
在 src/path/to/myVue.vue
中切换主题:
```vue
```
使用主题变量
在 src/path/to/myVue.vue
中使用主题变量:
```vue
```
下载地址
点击下载 【提取码: 4003】【解压密码: www.makuang.net】