Resolve Absolute / Alias Imports in Components with Storybook

风流意气都作罢 提交于 2021-01-23 06:03:12

问题


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:

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

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


回答1:


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",
]

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
}



回答2:


It seems that you need to create custom babel config for storybook. Include there your configurations of gatsby-plugin-alias-imports

https://storybook.js.org/docs/configurations/custom-babel-config/



来源:https://stackoverflow.com/questions/60634295/resolve-absolute-alias-imports-in-components-with-storybook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!