Next.js 与 SCSS 拆分为每个组件的文件

OrA*_*yag 5 sass reactjs next.js

我是 Next.js 的新手,经常使用 create-react-app(已弹出)。
通过 create-react-app 中的配置,我能够使用 SCSS 而非 CSS 模块方法,而是使用拆分的 SCSS 文件。

例如:

组件A.jsx

import React from 'react';
import './ComponentA.scss';

const ComponentA = () => {
} 
Run Code Online (Sandbox Code Playgroud)

组件B.jsx

import React from 'react';
import './ComponentB.scss';

const ComponentB = () => {
} 
Run Code Online (Sandbox Code Playgroud)

我已阅读以下内容:
https:
//medium.com/@vladymyr.pylypchatin/the-simple-way-to-use-scoped-and-global-scss-with-next-js-67cdb2d0c676 NextJS 组件级 SASS 样式

但是这些解决方案不符合我的需求。

我的问题:
有一种方法可以为每个组件编写本地 SCSS 文件,使用 put CSS-module 方法或<style jsx>方法,只需为每个组件导入 SCSS(如我添加的示例中)?,(我知道范围问题,我会自己手动管理类名)。
但是在构建包时将包保存到一个大的 CSS 文件中,就像 webpack 一样。

谢谢。

Mat*_*ron 4

您就快到了,您可以通过导入带有名称的 scss 文件来使用 css 模块。

import React from 'react';
import style from './ComponentA.scss';

const ComponentA = () => {
   return <div className={style.blockOne}>A</div>
} 
Run Code Online (Sandbox Code Playgroud)

import React from 'react';
import style from './ComponentB.scss';

const ComponentB = () => {
   return <div className={style.blockOne}>A</div>
} 
Run Code Online (Sandbox Code Playgroud)

然后,当您使用 typescript 构建应用程序时,它会将所有样式与您的逻辑放在同一个文件中,包括 css。

从打字稿生成应用程序的示例

...
var Button = function (props) {
    return (React.createElement("button", { form: props.form, type: props.type, onMouseOver: props.onMouseOver, className: "" + style$1.button + (props.className ? " " + props.className : "") + (props.disabled ? " " + style$1.disabled : "") + variableClass(style$1, props.removeShadow ? "removeShadow" : ""), onClick: props.onClick, disabled: props.disabled },
        props.leftIcon ? (React.createElement("div", { className: style$1.leftIcon }, props.leftIcon)) : null,
        React.createElement("div", { className: style$1.buttonValue }, props.children),
        props.icon ? React.createElement("div", { className: style$1.icon }, props.icon) : null));
};

var css_248z$2 = ".style-module_input__3-5Pc {\n  display: flex;\n  background: var(--input-background);\n  border-radius: var(--border-radius-input);\n  padding: 10px;\n  box-shadow: inset 0 2px 2px #0000001c; }\n  .style-module_input__3-5Pc input {\n    border: none;\n    width: 100%;\n    font-family: var(--txt-font);\n    background: var(--input-background);\n    padding: 0px; }\n    .style-module_input__3-5Pc input:focus {\n      outline: none; }\n  .style-module_input__3-5Pc .style-module_icon__1UUS9 {\n    padding-left: 5px;\n    color: var(--main-txt-color); }\n";
var style$2 = {"input":"style-module_input__3-5Pc","icon":"style-module_icon__1UUS9"};
styleInject(css_248z$2);
...
Run Code Online (Sandbox Code Playgroud)