You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Stencil.js中用Tailwind实现暗黑模式并在Storybook中测试?

在Stencil.js + Storybook中配置Tailwind CSS暗黑模式

一、基础配置:Tailwind开关类模式

先确保你的tailwind.config.js配置为类模式,这样能通过DOM类名手动控制暗黑模式,而非仅依赖系统媒体查询:

/** @type {import('tailwindcss').Config} */
module.exports = {
  darkMode: 'class', // 核心:用class模式替代默认的media
  content: [
    './src/**/*.{js,ts,jsx,tsx,html}',
    './.storybook/**/*.{js,ts,jsx,tsx,html}' // 务必包含Storybook相关文件
  ],
  // 其他Tailwind配置(主题、插件等)
}

二、Stencil.js组件适配

在组件模板中,确保内容容器能响应dark类。如果是全局组件(比如根组件),可以直接给根元素绑定主题类;单个组件则按需添加:

render() {
  return (
    <div class={this.isDark ? 'dark' : ''}>
      <div class="bg-white dark:bg-gray-900 text-gray-900 dark:text-white p-4">
        示例组件内容
      </div>
    </div>
  );
}

如果需要全局统一控制,可以通过Stencil的状态管理(比如@State()或全局store)维护主题状态,同步到根组件的类名上。

三、Storybook自定义主题切换

不需要依赖第三方插件,直接通过配置实现可控的主题切换:

1. 修改.storybook/preview.js

// 初始化主题:优先取本地存储,否则匹配系统设置
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const initialTheme = localStorage.getItem('theme') || (prefersDark ? 'dark' : 'light');

// 给根元素设置初始主题类
document.documentElement.classList.toggle('dark', initialTheme === 'dark');

// 注册Storybook工具栏的主题切换按钮
export const globalTypes = {
  theme: {
    name: 'Theme',
    description: '切换组件主题',
    defaultValue: initialTheme,
    toolbar: {
      icon: 'circlehollow', // 使用Storybook内置图标
      items: [
        { value: 'light', title: '亮色模式' },
        { value: 'dark', title: '暗色模式' },
      ],
      dynamicTitle: true,
    },
  },
};

// 监听主题切换,同步DOM类和本地存储
export const decorators = [
  (Story, context) => {
    const currentTheme = context.globals.theme;
    document.documentElement.classList.toggle('dark', currentTheme === 'dark');
    localStorage.setItem('theme', currentTheme);
    return Story();
  },
];

2. 确保样式加载正常

在.storybook/preview-head.html中引入你的Tailwind主样式文件(如果Stencil构建已自动注入,这步可跳过):

<link rel="stylesheet" href="/src/styles.css">

主样式文件styles.css需包含Tailwind基础指令:

@tailwind base;
@tailwind components;
@tailwind utilities;

四、验证效果

  • 启动Storybook后,点击工具栏的「Theme」按钮切换明暗,组件应自动应用dark:前缀的样式
  • 关闭系统深色模式,手动切换Storybook主题也能正常生效
  • 刷新页面后,主题状态会通过localStorage保留

内容的提问来源于stack exchange,提问作者Shrestha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:50:38