字节笔记本

2026年2月22日

Histoire 插件开发指南

本文介绍 Histoire 插件开发指南,帮助开发者创建自定义插件来扩展 Histoire 的功能。Histoire 是一个用于构建组件故事书(Storybook)的工具,支持 Vue 和 Svelte 框架。

准备工作

创建一个新的 npm 包,首先配置 package.json

json
{
  "name": "my-histoire-plugin",
  "version": "0.1.0",
  "description": "Histoire plugin",
  "license": "MIT",
  "author": {
    "name": "Guillaume Chau"
  },
  "repository": {
    "url": "https://github.com/Akryum/my-histoire-plugin.git",
    "type": "git",
    "directory": "packages/my-histoire-plugin"
  },
  "publishConfig": {
    "access": "public"
  },
  "type": "module",
  "exports": {
    ".": "./dist/index.js",
    "./*": "./*"
  },
  "main": "./dist/index.js",
  "module": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "rimraf dist && tsc -d",
    "watch": "tsc -d -w --sourceMap"
  },
  "dependencies": {
    "defu": "^6.0.0"
  },
  "devDependencies": {
    "histoire": "latest",
    "rimraf": "^3.0.0",
    "typescript": "^5.4.4"
  },
  "peerDependencies": {
    "histoire": "latest"
  }
}

重要提示:务必将 histoire 放在 peerDependencies 中。同时将其放在 devDependencies 中以便安装并从中导入内容。

TypeScript 配置

配置 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "moduleResolution": "node",
    "outDir": "dist",
    "rootDir": "src",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "removeComments": false,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "types": ["node"],
    "lib": ["ESNext", "DOM"],
    "sourceMap": false,
    "preserveWatchOutput": true,
    // Strict
    "noImplicitAny": false,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "strictBindCallApply": true,
    "strictFunctionTypes": true
  },
  "include": ["src"],
  "exclude": ["node_modules", "dist/**/*", "src/**/*.spec.ts"]
}

创建插件

创建 src/index.ts 文件:

typescript
import type { Plugin } from 'histoire'
import { defu } from 'defu'

export interface MyPluginOptions {
  // 在此定义选项
}

const defaultOptions: MyPluginOptions = {
  // 在此设置默认值
}

export function MyHistoirePlugin(options: MyPluginOptions = {}): Plugin {
  const finalOptions: MyPluginOptions = defu(options, defaultOptions)
  return {
    name: 'my-histoire-plugin',
    // 在此使用 Histoire 插件 API!
  }
}

使用插件

在 Histoire 配置中使用你的插件:

javascript
// histoire.config.js
import { defineConfig } from 'histoire'
import { MyHistoirePlugin } from 'my-histoire-plugin'

export default defineConfig({
  plugins: [
    MyHistoirePlugin({
      // 在此传入选项
    }),
  ],
})

插件 API 参考

更多插件 API 的详细信息,请参考 官方插件 API 文档

注意事项

警告:本文档和插件 API 正在开发中,可能会有变更。

官方插件示例

Histoire 官方提供了以下插件供参考:

  • @histoire/plugin-vue:Vue 3 支持插件
  • @histoire/plugin-nuxt:Nuxt 3 支持
  • @histoire/plugin-svelte:Svelte 3 和 SvelteKit 支持
  • @histoire/plugin-percy:使用 Percy 进行视觉回归测试
  • @histoire/plugin-screenshot:简单的视觉回归测试

相关链接

分享: