我正在構建一個 Gatsby Web 應用程式,其中每個組件都有一個.module.css檔案、一個.jsx檔案和一個stories.jsx檔案。我正在使用Gatsby 要求的以下匯入行(盡管沒有搖樹):
import * as styles from ./"filename.module.css"
然后,例如,如果我的filename.module.css被呼叫中有一個 CSS 選擇器.button,則關聯類名稱可以在styles物件中作為styles.button.
但是,同樣styles.button不會在 Storybook 中訪問正確的類名,它會回傳undefined. 檢查styles物件后,我看到類名包含default在styles. 我假設我必須以與 Gatsby 相同的方式處理匯入的方式配置 Storybook。我同樣發現在 Storybook 中使用以下匯入有效,但在 Gatsby 中無效:
import styles from ./"filename.module.css"
關于如何配置 Storybook 以與 Gatsby 相同的方式處理 CSS 模塊匯入的任何建議?理想情況下,我想避免 CSS 模塊搖樹,從一些快速測驗來看,這似乎不是問題的原因。
uj5u.com熱心網友回復:
是 webpack 決定了你的風格是否會改變你的風格,以及需要使用一個陳述句 ( import * as styles from "./filename.module.css") 或另一個 ( import styles from "./filename.module.css")。似乎您在每個專案上使用了不同的版本,因此 CSS 模塊的行為也發生了變化。
在所有選項中,我建議使用 Gatsby 需要的命名匯入,因為正如我所說,它允許 webpack 對你的樣式進行樹形調整,從而提高網站的性能。
代替:
import * as styles from "./filename.module.css"
最好匯入每個特定的 CSS 模塊并單獨應用它們:
import { style1, style2 } from "./filename.module.css"
摘自:帶有 PostCSS 8 的 Gatsby - 嘗試匯入錯誤:“component.module.css”不包含默認匯出(匯入為“樣式”)
使用第二種方法將是您專案的有效語法。
如果您仍想更改 Storybook 的行為(以避免搖樹),您可以嘗試如下配置 Storybook(在您的 中.storybook/main.js):
const path = require("path");
module.exports = {
// You will want to change this to wherever your Stories will live
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
addons: ["@storybook/addon-links", "@storybook/addon-essentials"],
core: {
builder: "webpack5",
},
webpackFinal: async (config) => {
// Prevent webpack from using Storybook CSS rules to process CSS modules
config.module.rules.find(
(rule) => rule.test.toString() === "/\\.css$/"
).exclude = /\.module\.css$/;
// Tell webpack what to do with CSS modules
config.module.rules.push({
test: /\.module\.css$/,
include: path.resolve(__dirname, "../src"),
use: [
{
loader: "style-loader",
options: {
modules: {
namedExport: true,
},
},
},
{
loader: "css-loader",
options: {
importLoaders: 1,
modules: {
namedExport: true,
},
},
},
],
});
// Transpile Gatsby module because Gatsby includes un-transpiled ES6 code.
config.module.rules[0].exclude = [/node_modules\/(?!(gatsby)\/)/];
// use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook
config.module.rules[0].use[0].options.plugins.push(
require.resolve("babel-plugin-remove-graphql-queries")
);
return config;
},
};
其他資源:
- 如何在故事書 6 中使用 css-modules
- 在 storybook v6.4 中加載 css 模塊類的問題
- https://github.com/storybookjs/storybook/issues/2320
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/459406.html
下一篇:將SVG剝離到其中的一部分
