[英]Resolve Absolute / Alias Imports in Components with Storybook
我正在使用gatsby-plugin-alias-imports
來進行絕對導入,如下所示: import { colors } from "@styles/theme";
這是在gatsby-config
中設置的。 現在我剛剛將故事書添加到我的項目中。 由於 storybook 不通過 gatsby 運行,別名導入將無法解析,我得到一個錯誤:
./src/components/Button/index.js 中的錯誤未找到模塊:錯誤:無法解析“@styles/theme”...
這是有道理的。 Storybook 不知道如何處理@styles...
- 但我該如何解決這個問題?
您需要通過將./src
添加到分辨率數組來配置 Storybook 的 Webpack 以遵循相同的指令。 在您的.storybook/webpack.config.js
文件中,將其添加到要導出的函數的主體中(假設您正在從第一個參數解構config
):
config.resolve.modules = [
path.resolve(__dirname, "..", "src"),
"node_modules",
]
完成后,您的webpack.config.js
文件應如下所示:
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
}
似乎您需要為故事書創建自定義 babel 配置。 在那里包含gatsby-plugin-alias-imports
https://storybook.js.org/docs/configurations/custom-babel-config/
您很有可能在這里找到您的解決方案。
解決 webpack 配置中的別名: https : //github.com/storybookjs/storybook/issues/3339
您需要告訴 storybook 的 webpack 配置來解析您在tsconfig.json
文件中設置的路徑別名。
在您的.storybook/main.js
文件中,您需要添加以下內容。
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
module.exports = {
"webpackFinal": async config => {
config.resolve.plugins.push(new TsconfigPathsPlugin())
return config
}
}
這會將tsconfig-paths-webpack-plugin
包添加到 storybook webpack 配置的解析插件中,並使用您的tsconfig.json
來解析路徑別名。
這也是在任何 webpack 配置文件中完成的確切方式。 我已經處理了很多使路徑別名工作的方法,這是絕對最簡單的方法,並且每次都可以使用。
如果您使用@storybook/vite-builder
。 這個簡潔的配置對我有用
const tsconfigPaths = require("vite-tsconfig-paths");
...
module.exports = {
...
framework: "@storybook/react",
core: {
"builder": "@storybook/builder-vite"
},
async viteFinal(config) {
config.plugins.push(tsconfigPaths.default());
return config;
},
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.