Docs
Storybook Docs

Webpack

Storybook Webpack 构建器是 Storybook 的默认构建器。此构建器使你能够为组件创建无缝的开发和测试体验,并提供一种高效的方式来独立开发 UI 组件,从而使你可以利用现有的 Webpack 配置和 Storybook。

¥Storybook Webpack builder is the default builder for Storybook. This builder enables you to create a seamless development and testing experience for your components and provides an efficient way to develop UI components in isolation allowing you to leverage your existing Webpack configuration with Storybook.

配置

¥Configure

默认情况下,Storybook 为 Webpack 提供零配置支持,并自动设置一个为处理最常见用例而创建的基线配置。但是,你可以扩展 Storybook 配置文件(即 .storybook/main.js|ts)并提供其他选项来提高 Storybook 的性能或根据你的需要进行自定义。下面列出了可用的选项及其使用方法示例。

¥By default, Storybook provides zero-config support for Webpack and automatically sets up a baseline configuration created to work with the most common use cases. However, you can extend your Storybook configuration file (i.e., .storybook/main.js|ts) and provide additional options to improve your Storybook's performance or customize it to your needs. Listed below are the available options and examples of how to use them.

选项描述
lazyCompilation启用 Webpack 的实验性 lazy compilation
core: { builder: { options: { lazyCompilation: true } } }
fsCache配置 Webpack 的文件系统 caching 功能
core: { builder: { options: { fsCache: true } } }
.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  core: {
    builder: {
      name: '@storybook/builder-webpack5',
      options: {
        fsCache: true,
        lazyCompilation: true,
      },
    },
  },
};
 
export default config;

覆盖默认配置

¥Override the default configuration

Storybook 的 Webpack 配置基于 Webpack 5,允许对其进行扩展以满足你的项目需求。如果你需要添加加载器或插件,你可以在 .storybook/main.js|ts 文件中提供 webpackFinal 配置元素。配置元素应导出一个函数,该函数接收基线配置作为第一个参数,并接收 Storybook 的选项对象作为第二个参数。例如:

¥Storybook's Webpack configuration is based on Webpack 5, allowing it to be extended to fit your project's needs. If you need to add a loader or a plugin, you can provide the webpackFinal configuration element in your .storybook/main.js|ts file. The configuration element should export a function that receives the baseline configuration as the first argument and Storybook's options object as the second argument. For example:

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  webpackFinal: async (config, { configType }) => {
    if (configType === 'DEVELOPMENT') {
      // Modify config for development
    }
    if (configType === 'PRODUCTION') {
      // Modify config for production
    }
    return config;
  },
};
 
export default config;

Storybook 启动时,会自动将配置合并到自己的配置中。但是,在提供 webpackFinal 配置元素时,你有责任自行合并配置。我们建议你负责任地处理对 config 对象的更改,同时保留 entryoutput 属性。

¥When Storybook starts, it automatically merges the configuration into its own. However, when providing the webpackFinal configuration element, you're responsible for merging the configuration yourself. We recommend that you handle the changes to the config object responsibly, preserving both the entry and output properties.

使用 Webpack 插件

¥Working with Webpack plugins

自定义 Storybook 配置的另一种方法是添加自定义插件或加载器来帮助进行代码优化、资源管理或其他任务。尽管如此,由于 Storybook 依赖 HtmlWebpackPlugin 来生成预览页面,我们建议你将更改附加到 config.plugins 数组,而不是覆盖它。例如:

¥Another way to customize your Storybook configuration is to add a custom plugin or loader to help with code optimization, asset management, or other tasks. Nevertheless, since Storybook relies on the HtmlWebpackPlugin to generate the preview page, we recommend that you append the changes to the config.plugins array rather than overwriting it. For example:

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
   webpackFinal: async (config) => {
    config.plugins.push(...);
    return config;
  },
};
 
export default config;

此外,当使用未明确包含特定文件扩展名(即通过 test 属性)的 Webpack 加载器时,你应该为该加载器 exclude 文件扩展名。

¥Additionally, when working with Webpack loaders that don't explicitly include specific file extensions (i.e., via the test property), you should exclude the .ejs file extension for that loader.

导入自定义 Webpack 配置

¥Import a custom Webpack configuration

如果你已经有需要在 Storybook 中重复使用的现有 Webpack 配置文件,你可以导入它并将其合并到默认配置中。例如:

¥If you already have an existing Webpack configuration file that you need to reuse with Storybook, you can import it and merge it into the default configuration. For example:

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
import custom from '../webpack.config.js'; // 👈 Custom Webpack configuration being imported.
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  webpackFinal: async (config) => {
    return {
      ...config,
      module: { ...config.module, rules: [...config.module.rules, ...custom.module.rules] },
    };
  },
};
 
export default config;

基于生成器搭建的项目可能需要你导入其特定的 Webpack 配置文件。我们建议你阅读生成器的文档以获取更多信息。

¥Projects scaffolded based on generators may require that you import their specific Webpack configuration files. We suggest reading your generator's documentation for more information.

调试 Webpack 配置

¥Debug Webpack configuration

如果你打算调试 Storybook 使用的 Webpack 配置,则可以使用 Storybook CLI 来帮助你。如果你在 开发模式 中运行,则可以使用以下命令:

¥If you intend to debug the Webpack configuration used by Storybook, you can use the Storybook CLI to help you. If you're running in development mode, you can use the following command:

npm run storybook -- --debug-webpack

此外,如果你正在生成 Storybook 的 静态构建,则可以使用以下命令:

¥Additionally, if you're generating a static build of your Storybook, you can use the following command:

npm run build-storybook -- --debug-webpack

编译器支持

¥Compiler support

Storybook 采用与编译器无关的打包方法。这允许你携带自己的应用打包器(例如,BabelSWC)并确保与基于 Webpack 5 的项目的庞大生态系统兼容。

¥Storybook takes a compiler-agnostic approach to bundling. This allows you to bring your own application bundler (e.g., Babel, SWC) and ensures compatibility within the vast ecosystem of Webpack 5-based projects.

SWC

如果你的项目是使用 SWC 构建的,请使用 @storybook/addon-webpack5-compiler-swc 插件。此插件增加了与 Webpack 5 项目的生态系统兼容性,同时保持了高性能。运行以下命令自动设置插件:

¥If your project is built using SWC, use the @storybook/addon-webpack5-compiler-swc addon. This addon increases ecosystem compatibility with Webpack 5 projects while maintaining high performance. Run the following command to set up the addon automatically:

npx storybook@latest add @storybook/addon-webpack5-compiler-swc

可以提供其他选项来自定义 SWC 配置。有关更多信息,请参阅 SWC API 文档

¥Additional options can be provided to customize the SWC configuration. See the SWC API documentation for more information.

启用后,此插件会调整 Webpack 配置以使用 swc-loader 作为 JavaScript 和 TypeScript 文件。此外,它将检测并使用你项目的 SWC 配置。

¥When enabled, this addon adjusts the Webpack configuration to use the swc-loader for JavaScript and TypeScript files. Additionally, it will detect and use your project's SWC configuration.

Babel

如果你正在处理依赖 Babel 工具来提供对特定功能(包括 TypeScript 或其他现代 JavaScript 功能)支持的项目,则可以使用 @storybook/addon-webpack5-compiler-babel 插件将它们包含在 Storybook 中,以确保与你的项目兼容。运行以下命令自动设置插件:

¥If you're working with a project that relies on Babel's tooling to provide support for specific features, including TypeScript or other modern JavaScript features, you can use the @storybook/addon-webpack5-compiler-babel addon to allow you to include them in your Storybook to ensure compatibility with your project. Run the following command to set up the addon automatically:

npx storybook@latest add @storybook/addon-webpack5-compiler-babel

可以提供其他选项来自定义 Babel 配置。有关更多信息,请参阅 babel API 文档,或者如果你正在开发插件,请参阅 babelDefault 文档

¥Additional options can be provided to customize the Babel configuration. See the babel API documentation for more information, or if you're working on an addon, the babelDefault documentation for more information.

启用后,此插件将调整 Webpack 配置以使用 babel-loader 作为 JavaScript 和 TypeScript 文件的默认加载器。此外,它将检测并使用你项目的 Babel 配置。

¥When enabled, the addon will adjust the Webpack configuration to use the babel-loader as the default loader for JavaScript and TypeScript files. Additionally, it will detect and use your project's Babel configuration.

故障排除

¥Troubleshooting

TypeScript 模块未在 Storybook 中解析

¥TypeScript modules are not resolved within Storybook

Storybook 的默认 Webpack 配置支持大多数项目设置,无需任何其他配置。但是,根据你的项目配置或所选框架,你可能会遇到 TypeScript 模块在 Storybook 中无法解析的问题,当从你的 tsconfig 文件 别名时。如果你遇到此问题,你可以按如下方式使用 tsconfig-paths-webpack-plugin扩展 Storybook 的 Webpack 配置

¥Storybook's default Webpack configuration provides support for most project setups without the need for any additional configuration. Nevertheless, depending on your project configuration, or the framework of choice, you may run into issues with TypeScript modules not being resolved within Storybook when aliased from your tsconfig file. If you encounter this issue, you can use tsconfig-paths-webpack-plugin while extending Storybook's Webpack config as follows:

.storybook/main.ts
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
import TsconfigPathsPlugin from 'tsconfig-paths-webpack-plugin';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  webpackFinal: async (config) => {
    if (config.resolve) {
      config.resolve.plugins = [
        ...(config.resolve.plugins || []),
        new TsconfigPathsPlugin({
          extensions: config.resolve.extensions,
        }),
      ];
    }
    return config;
  },
};
 
export default config;

但是,如果你使用的是提供默认别名配置的框架(例如 Next.js、Nuxt),并且想要配置 Storybook 以使用相同的别名,则可能不需要安装任何其他软件包。相反,你可以扩展 Storybook 的默认配置以使用框架提供的相同别名。例如,要为 @ 导入路径设置别名,你可以将以下内容添加到你的 .storybook/main.js|ts 文件:

¥However, if you're working with a framework that provides a default aliasing configuration (e.g., Next.js, Nuxt) and you want to configure Storybook to use the same aliases, you may not need to install any additional packages. Instead, you can extend the default configuration of Storybook to use the same aliases provided by the framework. For example, to set up an alias for the @ import path, you can add the following to your .storybook/main.js|ts file:

.storybook/main.ts
import path from 'path';
// Replace your-framework with the framework you are using (e.g., react-webpack5, vue3-vite)
import type { StorybookConfig } from '@storybook/your-framework';
 
const config: StorybookConfig = {
  framework: '@storybook/your-framework',
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'],
  webpackFinal: async (config) => {
    if (config.resolve) {
      config.resolve.alias = {
        ...config.resolve.alias,
        '@': path.resolve(__dirname, '../src'),
      };
    }
    return config;
  },
};
 
export default config;

预打包资源不会显示在 Storybook UI 中

¥Pre-bundled assets do not show in the Storybook UI

由于 Storybook 依赖 esbuild 来构建其内部管理器,对使用 managerWebpack 打包资源的支持将不再对 Storybook UI 产生影响。我们建议从你的 Storybook 配置文件中删除现有的 managerWebpack 配置元素,并事先将图片或 CSS 以外的资源打包到 JavaScript 中。

¥As Storybook relies on esbuild to build its internal manager, support for bundling assets with the managerWebpack will no longer have an impact on the Storybook UI. We recommend removing existing managerWebpack configuration elements from your Storybook configuration file and bundling assets other than images or CSS into JavaScript beforehand.

Storybook 无法与 Webpack 一起运行 4

¥Storybook doesn't run with Webpack 4

对 Webpack 4 的支持已被删除,不再维护。如果你正在升级 Storybook,它将自动使用 Webpack 5 并尝试迁移你的配置。但是,如果你使用的是自定义 Webpack 配置,则可能需要对其进行更新以与 Webpack 5 配合使用。迁移过程是必要的,以确保你的项目使用最新版本的 Storybook 顺利运行。你可以按照 Webpack website 上提供的说明来更新你的配置。

¥Support for Webpack 4 has been removed and is no longer being maintained. If you're upgrading your Storybook, it will automatically use Webpack 5 and attempt to migrate your configuration. However, if you're working with a custom Webpack configuration, you may need to update it to work with Webpack 5. The migration process is necessary to ensure that your project runs smoothly with the latest version of Storybook. You can follow the instructions provided on the Webpack website to update your configuration.

了解更多有关构建器的信息

¥Learn more about builders

  • Vite 构建器 用于与 Vite 打包

    ¥Vite builder for bundling with Vite

  • 用于与 Webpack 打包的 Webpack 构建器

    ¥Webpack builder for bundling with Webpack

  • 构建器 API 用于构建 Storybook 构建器

    ¥Builder API for building a Storybook builder