如何强制Storybook重新渲染组件?Server项目模板热重载求助
Storybook Server类型项目监听外部模板文件并触发预览刷新
方法1:通过Storybook通道+文件监听器强制刷新
这种方法直接监听模板文件变更,通过Storybook内部通道通知预览界面调用刷新API,能确保预览实时更新。
- 安装文件监听工具
chokidar:
npm install chokidar --save-dev
- 修改
.storybook/main.js,添加模板文件监听器并发送刷新事件:
const chokidar = require('chokidar'); const path = require('path'); const { addons } = require('@storybook/addons'); const channel = addons.getChannel(); module.exports = { framework: { name: '@storybook/server-webpack5', options: {}, }, async init() { // 替换为你的实际模板文件路径,支持通配符 const templateWatchPath = path.resolve(__dirname, '../src/templates/**/*.hbs'); const watcher = chokidar.watch(templateWatchPath, { ignoreInitial: true }); watcher.on('change', (filePath) => { console.log(`模板文件已更新: ${filePath}`); // 向预览界面发送刷新信号 channel.emit('template-file-updated'); }); }, };
- 修改
.storybook/preview.js,监听通道事件并触发预览刷新:
import { useEffect } from 'react'; import { useStorybookApi } from '@storybook/preview-api'; import { addons } from '@storybook/addons'; export const preview = { decorators: [ (Story) => { const storybookApi = useStorybookApi(); const channel = addons.getChannel(); useEffect(() => { const handleTemplateChange = () => { // 调用API强制刷新当前Story预览 storybookApi.refresh(); }; channel.on('template-file-updated', handleTemplateChange); return () => channel.off('template-file-updated', handleTemplateChange); }, [storybookApi, channel]); return <Story />; }, ], };
方法2:配置Webpack监听模板文件
通过扩展Webpack的监听配置,让Webpack跟踪模板文件变更,触发编译后Storybook可能自动刷新(部分场景下生效,若Server类型Storybook不触发则优先用方法1):
修改.storybook/main.js:
const path = require('path'); module.exports = { framework: { name: '@storybook/server-webpack5', options: {}, }, webpackFinal: async (config) => { // 让Webpack监听模板文件路径 config.watchOptions = { ...config.watchOptions, ignored: [ ...(config.watchOptions?.ignored || []), // 排除默认忽略的,同时包含模板文件(注意!表示反向排除) '!../src/templates/**/*', ], }; // 添加空loader让Webpack识别模板文件(无需编译,仅用于跟踪变更) config.module.rules.push({ test: /\.(hbs|html|twig)$/, // 替换为你的模板文件后缀 use: ['null-loader'], }); return config; }, };
需要先安装null-loader:
npm install null-loader --save-dev
内容的提问来源于stack exchange,提问作者Russ Back
相关产品推荐
相关产品推荐

