使用Storybook解决组件中的绝对/别名导入问题 [英] Resolve Absolute / Alias Imports in Components with Storybook

查看:333
本文介绍了使用Storybook解决组件中的绝对/别名导入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 gatsby-plugin-alias-imports 进行绝对导入,如下所示: import {colors} from"@ styles/theme"; 这是在 gatsby-config 中设置的.现在,我刚刚将故事书添加到我的项目中.由于故事书未通过gatsby运行,因此别名导入无法解析,并且出现错误:

I'm using gatsby-plugin-alias-imports to be able to do absolute imports like so: import { colors } from "@styles/theme"; This is set up in the gatsby-config. Now I've just added storybook to my project. Since storybook doesn't run through gatsby, the alias imports won't resolve and I get an error:

./src/components/Button/index.js中的

ERROR找不到模块:错误:无法在...中解析"@ styles/theme"

ERROR in ./src/components/Button/index.js Module not found: Error: Can't resolve '@styles/theme' in ...

这很有道理.故事书不知道如何处理 @styles ... -但是我该如何解决?

This makes sense. Storybook doesn't know what to do with @styles... - but how can I fix this?

推荐答案

您需要通过将 ./src 添加到resolutions数组来配置Storybook的Webpack来遵循相同的指令.在您的 .storybook/webpack.config.js 文件中,将此文件添加到要导出的函数的主体中(假设您要从第一个参数解构 config ):

You need to configure Storybook's Webpack to follow the same directive by adding ./src to the resolutions array. In your .storybook/webpack.config.js file, add this to the body of the function being exported (assuming you're destructuring config from the first argument):

config.resolve.modules = [
  path.resolve(__dirname, "..", "src"),
  "node_modules",
]

完成后,您的 webpack.config.js 文件应如下所示:

Your webpack.config.js file should look something like this when you're done:

const path = require("path")

module.exports = ({ config }) => {
  // a bunch of other rules here

  config.resolve.modules = [
    path.resolve(__dirname, "..", "src"),
    "node_modules",
  ]

  // Alternately, for an alias:
  config.resolve.alias = {
    "@styles": path.resolve(__dirname, "..", "src", "styles")
  }

  return config
}

这篇关于使用Storybook解决组件中的绝对/别名导入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆