安装 • 妇女 使用量 • 妇女 选项 • 妇女 他们的博士们..
停止的 Vite 插件
@42-central/ui-react
应用程序在加载时闪出错误的主题。 里面放的是工具箱的主题动画脚本
在顶端 <head> 内 index.html,两者中 vite dev 财务报告和审定财务报表 vite build。 。 。 .
为什么
useTheme() 存储访客的 "light" | "dark" | "system" 选择和选择
保留 data-theme 打开 <html> 同步。 只有在第一次喷漆后才会反应,
虽然. 所以,没有帮助,一个黑暗模式的访客 看到一个光框之前
钩子赶上了.
在下一个.js, <ThemeScript /> 覆盖从服务器渲染的漏洞。 一个虚拟
SPA 没有服务器渲染,所以脚本必须坐入 index.html 块
解析。 这不可能 type="module",因为 Vite 推迟模块
剧本,而闪光又回来了. 此插件注入经典内线
<script> 通过Vite的 transformIndexHtml 钩子,所以你从来不编辑
HTML是手边的.
安装
安装为 dev 依赖, 套件旁边 :
npm install -D @42-central/vite-plugin-theme
pnpm add -D @42-central/vite-plugin-theme
yarn add --dev @42-central/vite-plugin-theme
bun add --dev @42-central/vite-plugin-theme
vite 7或8是一种同龄依赖. 插件用
@42-central/ui-react,它将其列为自己的依赖。 都留着
同版本的软件包:它们一起发行.
使用量
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { themeInitPlugin } from "@42-central/vite-plugin-theme";
export default defineConfig({
plugins: [react(), themeInitPlugin()],
});
然后读取并更改主题 从任何组件与工具包的钩:
import { useTheme } from "@42-central/ui-react";
export function ThemeToggle() {
const { resolvedTheme, setMode } = useTheme();
return (
<button onClick={() => setMode(resolvedTheme === "dark" ? "light" : "dark")}>
Toggle theme
</button>
);
}
选项
themeInitPlugin(options?) 和工具箱一样
buildThemeInitScript()附加时 nonce数字 :
| 选项 | 类型 | 默认 | 它会做什么 |
|---|---|---|---|
storageKey | string | "ui-theme" | localStorage 键,该键持有存储模式. |
defaultColorScheme | "light" | "dark" | "system" | "system" | 尚未存储时使用的模式 . |
forceColorScheme | "light" | "dark" | – 说吧 – | 绑定主题并忽略存储和OS偏好. |
attribute | "data-theme" | "class",或者其中的数组 | "data-theme" | 写什么 <html>页:1 data-theme 属性, a .dark 或两者兼有. |
nonce | string | – 说吧 – | 注入的CSP 非ce <script>。 。 。 . |
保持与 useTheme()
没有提供者持有此配置, 所以脚本和钩子
无法分享 过 storageKey, (中文(简体) ), defaultColorScheme, (中文(简体) ), forceColorScheme
财务报告和审定财务报表 attribute 与 相同数值 到插件和每个
useTheme() 电话 如果两者不同,剧本和钩子先有分歧
装入.
// vite.config.ts
themeInitPlugin({ forceColorScheme: "dark", attribute: ["class", "data-theme"] });
// anywhere in the app
useTheme({ forceColorScheme: "dark", attribute: ["class", "data-theme"] });
共享 const THEME_OPTIONS = { … } 两个文件导入最简单
如何保持他们的一致.
内容安全政策
如果您的 CSP 屏蔽了内置脚本, 请通过您的服务器在
script-src 指令 :
themeInitPlugin({ nonce: "{{CSP_NONCE}}" });
值进入已建 index.html 逐字记录。 使用任意占位符
您的服务器或边缘功能将替换每个请求.
注射什么药
一个标签,第一个在 <head>数字 :
<head>
<script>/* ~600 bytes: read localStorage, resolve "system", set data-theme */</script>
<!-- the rest of your head -->
</head>
剧本运行一次,没有收听者。 选择操作系统
装入后继续运行 useTheme()这是工作.
不使用维特?
这个 反射读取
涵盖替代品:预建 theme-init.js 复制到 public/, (中文(简体) ),
或粘贴输出 buildThemeInitScript() 手边。 Next.js 应用程序使用
<ThemeScript /> 换句话说.