如何使用 Tailwindcss、ReactJS 和 Typescript 设置 Storybook

won*_*ngz 1 typescript reactjs storybook tailwind-css

如何设置 Storybook 以便它解析 Tailwindcss 样式并解析绝对路径?

注意:这是根据此允许的自记录问题/答案。这需要一段时间才能弄清楚,我相信很多其他人也会遇到这个问题。

won*_*ngz 6

为了解析 Storybook 中的路径,我们将使用 tsconfig 作为源。我们假设您已经安装了带有 typescript 模板的 ReactJS 项目。

设置绝对路径

1.在typescript中定义绝对路径

在 中的“路径”下添加绝对路径tsconfig.js

// tsconfig.json

{
  "compilerOptions": {
    // ...
    "baseUrl": "src",
    "paths": {
      "#assets/*": ["./assets/*"],
      "#components/*": ["./components/*"],
      // etc.
    }
  }
  "include": ["src"]
}
Run Code Online (Sandbox Code Playgroud)

2. 扩展 tsconfig 绝对路径以在 Storybook 中工作

从 npm安装tsconfig-paths-webpack-plugin。截至撰写本文时,每周下载量已达数百万次。

$ npm install -D tsconfig-paths-webpack-plugin
// or
$ yarn add -D tsconfig-paths-webpack-plugin
Run Code Online (Sandbox Code Playgroud)

通过.storybook/main.js将以下内容添加到 module.exports 来扩展 tsconfig 路径解析。

$ npm install -D tsconfig-paths-webpack-plugin
// or
$ yarn add -D tsconfig-paths-webpack-plugin
Run Code Online (Sandbox Code Playgroud)

来源

3. 解析 Storybook 中的 Tailwind 风格

在文件顶部添加以下两行代码.storybook/preview.js

// .storybook/main.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  // Add the following block of code in addition to what's existing
  "webpackFinal": async (config) => {
    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin({
        extensions: config.resolve.extensions,
      }),
    ];
    return config;
  },
};
Run Code Online (Sandbox Code Playgroud)

来源

你的 tailwindcss 现在应该解析了。

附加文件

对于 Tailwind v3+,请确保您tailwind.config.js没有清除选项并且没有明确声明 JIT。我的看起来像这样:

// .storybook/preview.js

import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
import 'tailwindcss/tailwind.css';
Run Code Online (Sandbox Code Playgroud)