React 中的 Firefox Web 扩展,无法解析 CSS - "You may need an appropriate loader to handle this file type"

Firefox Web Extension in React, unable to parse CSS - "You may need an appropriate loader to handle this file type"

在我的代码中,我在主 App 文件中导入 index.cssimport './index.css';。但是,当我尝试构建应用程序时,出现以下错误,即使我知道 CSS 文件本身没有问题:

ERROR in ./src/index.css 1:5
Module parse failed: Unexpected token (1:5)
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
> body {
|   margin: 0;
|   font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',

这是我的当前 webpack.config.js,我不确定它缺少什么或应该添加什么:

const HTMLPlugin = require('html-webpack-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const path = require('path');
const ExtensionReloader = require('webpack-extension-reloader');
const ManifestVersionSyncPlugin = require('webpack-manifest-version-sync-plugin');

module.exports = {
  entry: {
    options: './src/options.js',
    popup: './src/popup.js',
    content: './src/content.js',
    background: './src/background.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'build'),
  },
  resolve: {
    extensions: ['.js', '.jsx', '.css'],
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    alias: {
      react: 'preact/compat',
      'react-dom': 'preact/compat',
    },
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
          },
        ],
      },
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
  plugins: [
    new HTMLPlugin({
      chunks: ['options'],
      filename: 'options.html',
      title: 'Options page title',
    }),
    new HTMLPlugin({
      chunks: ['popup'],
      filename: 'popup.html',
    }),
    new CopyPlugin([
      { from: './src/_locales/', to: './_locales' },
      { from: './src/assets', to: './assets' },
      { from: './src/manifest.json', to: './manifest.json' },
    ]),
    new ExtensionReloader({
      manifest: path.resolve(__dirname, './src/manifest.json'),
    }),
    new ManifestVersionSyncPlugin(),
  ],
  optimization: {
    minimize: true,
  },
  mode: 'production',
  stats: 'minimal',
};

您的 webpack 配置尚未设置为处理 .css 导入。如果这主要用于 production 环境,则添加这些包:

mini-css-extract-plugin

css-loader

npm install -D mini-css-extract-plugin css-loader

yarn add -D mini-css-extract-plugin css-loader

然后require mini-css-提取包:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

将此添加到您的 webpack rules 配置中 .jsx 规则之后:

{
  test: /\.css$/,
  use: [MiniCssExtractPlugin.loader, "css-loader"],
}

最后,将其添加到您的 webpack 列表中 plugins:

new MiniCssExtractPlugin()

上面的两个链接包含有关自定义选项和自定义设置的更多信息。如果您 运行 有任何其他 CSS 相关问题,我建议您读一读。