在我的 gatsby 项目中,我收到了将样式导入我的文件的警告pages/index.js
import { Link } from "gatsby"
import React from "react"
import Layout from "../components/Layout"
import style from "../styles/home.module.css"
export default function Home() {
return (
<Layout>
<section className={style.header}>
<div>
<h2>Design</h2>
<h3>Develop & deploy</h3>
<p>Become web ninja</p>
<Link to="/projects" className={style.btn}>
My Portfolio Projects
</Link>
</div>
<img src="banner.png" alt="site banner" style={{ maxWidth: "80%" }} />
</section>
</Layout>
)
}
warn Attempted import error: '../styles/home.module.css' does not contain a default export (imported as 'style').
我正在使用模块样式表。所以 home.module.css 看起来像这样
.header {
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 40px;
align-items: center;
}
.header h2 {
font-size: 4em;
}
.header h3 {
font-size: 3em;
font-weight: 400;
margin-bottom: 20px;
}
.btn {
display: inline-block;
background: #d42990;
padding: 10px 16px;
border-radius: 10px;
margin-top: 20px;
font-weight: 500;
}
这是我用的gatsby版本
"gatsby": "^3.0.3",
"gatsby-source-filesystem": "^3.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1"
工作树看起来像
.
├── components
│ ├── Layout.js
│ └── Navbar.js
├── node
│ ├── bar.txt
│ └── foo.txt
├── pages
│ ├── 404.js
│ ├── about.js
│ ├── index.js
│ └── projects
│ └── index.js
└── styles
├── global.css
├── home.module.css
└── project.module.css
我不知道是什么导致了我运行时的错误
gatsby develop
它抛出的错误是
The page didn't server render (SSR) correctly
最初gatsby版本是v2,我在我的项目中升级到v3。所以我不知道SSR错误的原因是什么。如果我跳过 SSR 它会抛出像
这样的错误_styles_home_module_css__WEBPACK_IMPORTED_MODULE_3__.default is undefined
有人可以帮我吗?
你可以试试这个:
import * as style from "../styles/home.module.css"
https://www.gatsbyjs.com/docs/tutorial/part-two/#-build-a-new-page-using-css-modules
2023 年更新
在@Sephyre 的回答之后,Gatsby 还在他们的变更日志中注释现在不鼓励
import * as foo from "./some-file.module.css"
,因为Webpack 在编译样式时不能摇动。
相反,他们推荐对象解构。您可以对 CSS 和 SASS 文件使用这种方法:
/* testCSS.module.css */
.testClass {
display: block;
}
#test-id {
display: block;
}
// testSCSS.module.scss
$font-base: "Lato", "Helvetica Neue", Helvetica, Arial, sans-serif;
:export {
fontBase: $font-base;
}
import { testClass, testId } from '../styles/themes/testCSS.module.css';
import { fontBase } from '../styles/themes/testSCSS.module.scss';
import Layout from './layout';
export default function PageLayout({ children }) {
return (
<Layout>
<p>{testClass}</p>
<p>{testId}</p>
<p>{testId}</p>
</Layout>
);
}
只是为了增加混乱,您不要在导入的 CSS/SASS 变量名称前加上
$
:
<p>{$testClass}</p>
...
$testClass is not defined!