我正在开发一个简单的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
./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;
}
答案 0 :(得分:3)
这是我解决问题的方法。 ?
随着Next.js 9.3的发布,不再需要@zeit/next-sass
和@zeit/next-css
。 ?
我还执行以下操作:
styled-jsx-plugin-sass node-sassa
添加为dev-dep .babelrc
文件并添加以下内容:{
"presets": [
[
"next/babel",
{
"styled-jsx": {
"plugins": ["styled-jsx-plugin-sass"]
}
}
]
]
}
所以我有两种选择:
<style jsx>
上添加我的sass / scss <ComponentName>.module.scss
第二个选择是A的麻烦,您需要import styles from './ComponentName.module.scss
并将元素类添加为className={styles.ComponentName}
或className={styles['ComponentName-button']}
。 ?