Webpack 样式加载器无法加载 sass 个模块

Webpack style loader can not load sass modules

我有一个 React 应用程序,我想要 sass 和 css 支持。问题是当我导入 sass 或 css 模块时,它没有应用于标签。我的意思是看下面的代码我想要使用样式的第 2 种方式:

import React from 'react';
import PropTypes from 'prop-types';
import style from './index.module.scss';
import { Header, Footer, Container } from '..';
import './style.scss'; // 1. this way is applying
import style from './style.scss'; // 2. this way is not applying



export const Layout = ({ children }) => (
  <div className="content"> // 1. this way is applying
    <Header />
    <Container>
      <div className={style.content}> // 2. this way is not applying
        {children}
      </div>
    </Container>
    <Footer />
  </div>
);

Layout.propTypes = {
  children: PropTypes.any.isRequired,
};

export default Layout;

这是我的 webpack:

const path = require('path');
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const cones = require('./cones.json');

module.exports = {
  mode: 'development',
  entry: './src/index',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'),
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new CopyWebpackPlugin([{ from: 'public/index.html' }]),
  ],
  devServer: {
    port: 3000,
    contentBase: path.join(__dirname, './public'),
    hot: true,
    open: true,
    historyApiFallback: true,
    before(app) {
      app.get('/api/cones', (req, res) => {
        res.json(cones);
      });
    },
  },
  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',
        ],
      },
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx', '.scss'],
  },
};

我认为 style-loader 有问题,无法以这种方式加载样式模块。

"number 2 way" 称为 CSS Modules。为了使用它,您需要在 css-loader 的选项中打开 modules。看看这是否有效:

{
  test: /\.s[ac]ss$/i,
  loader: [
    'style-loader',
    {
      loader: 'css-loader',
      options: {
        modules: true,
      },
    },
    'sass-loader',
  ],
},