简体   繁体   English

如何在不是 Next.js 的 React 中加载 scss?

[英]How to load scss in React which is not Next.js?

We have a component which is used both in Next.js project and a React project.我们有一个在 Next.js 项目和 React 项目中都使用的组件。 Component has a css module made with scss.组件有一个用 scss 制成的 css 模块。 In Next.js it is fairly easy to use it.在 Next.js 中使用它相当容易。

https://www.freecodecamp.org/news/how-to-use-sass-with-css-modules-in-next-js/ https://www.freecodecamp.org/news/how-to-use-sass-with-css-modules-in-next-js/

Only need to add sass module.只需添加sass模块即可。 Strange tough when I use it in React based Wordpress plugin, I got following error:当我在基于 React 的 Wordpress 插件中使用它时,我遇到了以下错误:

ERROR in ./tikexModule/styles/buyTicket.module.scss 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> .section1 {
|   display: flex;
|   align-items: center;
 @ ./tikexModule/components/BuyTicket/PricingOptionInvoiceItemsFormFieldsCheckboxes.tsx 4:0-56 160:15-26

it can not handle scss .它无法处理scss Why?为什么? I added sass to both.我将sass添加到两者中。

Webpack needs to be configured to load the specified extention. Webpack 需要配置加载指定扩展。

First you need to instal sass loader and sass webpack with:首先,您需要安装 sass 加载器和 sass webpack :

npm install sass-loader sass webpack --save-dev

Then in your webpack.config.js you need to configure it:然后在你的webpack.config.js你需要配置它:

module.exports = {
  module: {
    rules: [
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          "style-loader",
          // Translates CSS into CommonJS
          "css-loader",
          // Compiles Sass to CSS
          "sass-loader",
        ],
      },
    ],
  },
};

Webpack has great documentation, have a look: https://webpack.js.org/loaders/sass-loader/ Webpack 有很好的文档,看看: https://webpack.js.org/loaders/sass-loader/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM