简体   繁体   English

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

[英]How to setup Storybook with Tailwindcss, ReactJS and Typescript

How do you setup Storybook so that it parses Tailwindcss styles and also parses absolute paths?您如何设置 Storybook 以便解析 Tailwindcss styles 并解析绝对路径?

Note: This is a self-documenting question/answer allowed as per this .注意:这是根据this允许的自记录问题/答案。 This took a while to figure out and I'm sure many others will encounter this.这需要一段时间才能弄清楚,我相信很多其他人都会遇到这个问题。

To resolve paths in Storybook, we'll be using tsconfig as the source.为了解析 Storybook 中的路径,我们将使用 tsconfig 作为源。 We assume you have installed a ReactJS project with the typescript template already.我们假设你已经安装了一个带有 typescript 模板的 ReactJS 项目。

Setting Absolute Paths设置绝对路径

1. Define absolute paths in typescript 1.在打字稿中定义绝对路径

Add your absolute paths under "paths" in tsconfig.js .tsconfig.js的“路径”下添加绝对路径。

// tsconfig.json

{
  "compilerOptions": {
    // ...
    "baseUrl": "src",
    "paths": {
      "#assets/*": ["./assets/*"],
      "#components/*": ["./components/*"],
      // etc.
    }
  }
  "include": ["src"]
}

2. Extend the tsconfig absolute paths to work in Storybook 2. 扩展 tsconfig 绝对路径以在 Storybook 中工作

Install the tsconfig-paths-webpack-plugin from npm.从 npm 安装tsconfig-paths-webpack-plugin Has millions of weekly downloads at time of writing.在撰写本文时,每周有数百万的下载量。

$ npm install -D tsconfig-paths-webpack-plugin
// or
$ yarn add -D tsconfig-paths-webpack-plugin

Under .storybook/main.js extend the tsconfig path resolution by adding the following to your module.exports..storybook/main.js下,通过将以下内容添加到您的 module.exports 来扩展 tsconfig 路径解析。

// .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;
  },
};

Source 资源

Parsing Tailwind Styles in Storybook解析 Storybook 中的 Tailwind 样式

Add the following two lines of code at the top of your .storybook/preview.js file..storybook/preview.js文件的顶部添加以下两行代码。

// .storybook/preview.js

import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
import 'tailwindcss/tailwind.css';

Source资源

Your tailwindcss should parse now.您的 tailwindcss 现在应该解析。

Additional files附加文件

For Tailwind v3+, make sure your tailwind.config.js doesn't have the purge option and doesn't explicitly state JIT.对于 Tailwind v3+,请确保您的tailwind.config.js没有清除选项并且没有明确声明 JIT。 Mine looks like this:我的看起来像这样:

// tailwind.config.js

module.exports = {
    content: [
        "./src/**/*.{js,jsx,ts,tsx}"
    ],
    theme: {
        extend: {},
    },
    plugins: [],
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM