NextJS组件级别SASS样式 [英] NextJS component level SASS styling
本文介绍了NextJS组件级别SASS样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一个简单的NextJS应用程序,但我在使用SASS/SCSS进行组件级样式设计时遇到了问题。当用户第一次登陆页面时,一切看起来都很好,但当用户导航到一个页面/about
或从/about
导航到/
时,组件样式没有呈现,用户需要刷新页面才能看到样式🤔
⚙️设置
./package.json
"dependencies": {
"@zeit/next-css": "1.0.1",
"@zeit/next-sass": "1.0.1",
"autoprefixer": "^9.7.0",
"next": "^9.3.1",
"node-sass": "4.13.1",
"react": "^16.13.0",
"react-dom": "^16.13.0",
"webpack": "^4.42.0"
}
./next.config.js
const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');
module.exports = withCss(
withSass({
webpack(config) {
config.module.rules.push({
test: /.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
use: {
loader: 'url-loader',
options: {
limit: 100000,
},
},
});
return config;
},
}),
);
./postcss.config.js
const autoprefixer = require('autoprefixer');
module.exports = {
plugins: [autoprefixer],
};
📄页面
./pages/index.js
import React from 'react';
import Layout from '../components/Layout';
import Home from '../components/Home';
class Index extends React.PureComponent {
render() {
<Layout>
<Home />
</Layout>
}
}
export default Index;
./pages/about.js
import React from 'react';
import Layout from '../components/Layout';
import Company from '../components/Company';
class About extends React.PureComponent {
render() {
<Layout>
<Company />
</Layout>
}
}
export default About;
📦组件
./components/Layout.js
import React from 'react';
import AppBar from '../AppBar/AppBar';
import './Layout.scss';
class Layout extends React.PureComponent {
render() {
const { children } = this.props;
return (
<>
<AppBar />
<main className="Layout">
{children}
</main>
</>
);
}
}
export default Layout;
./components/Layout.scss
.Layout {
background: #f00;
}
./components/AppBar.js
import Link from 'next/link';
import './AppBar.scss';
export default () => (
<header className="AppBar">
<Link href="/">
<a>Home</a>
</Link>
<Link href="/about">
<a>About</a>
</Link>
</header>
)
./components/AppBar.scss
.AppBar {
background: #0f0;
}
./components/Home.js
import './Home.scss';
export default () => (
<div className="Home">Home</div>
)
./components/Home.scss
.Home {
background: #00f;
}
./components/Company.js
import './Company.scss';
export default () => (
<div className="Company">Company</div>
)
./components/Company.scss
.Company {
background: #ff0;
}
推荐答案
这就是我解决问题的方法。🎉
随着Next.js 9.3的发布,不再需要@zeit/next-sass
&;@zeit/next-css
。👏
我还执行以下操作:
- 添加
styled-jsx-plugin-sass node-sassa
作为开发人员 - 创建
.babelrc
文件并添加以下内容:
{
"presets": [
[
"next/babel",
{
"styled-jsx": {
"plugins": ["styled-jsx-plugin-sass"]
}
}
]
]
}
因此我有两个选择:
- 将我的sass/scss添加到
<style jsx>
- 将我的组件sass/scss文件重命名为
<ComponentName>.module.scss
import styles from './ComponentName.module.scss
并添加元素类作为className={styles.ComponentName}
或className={styles['ComponentName-button']}
。🧐
这篇关于NextJS组件级别SASS样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文