简体   繁体   English

Webpack CSS 模块错误 如何正确加载 css

[英]Webpack CSS Module Error how to load css properly

Hey guys I'm trying to run this project using Webpack with the CSS loader but I keep getting this error:嘿伙计们,我正在尝试使用 Webpack 和 CSS 加载程序运行这个项目,但我一直收到这个错误:

ERROR in ./src/component/list-view/list-view.css 1:3
Module parse failed: Unexpected token (1:3)
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
> h2 {
|     color: #ff0000;
| }

This is a plain JS project.这是一个普通的 JS 项目。 My Webpack config looks like this:我的 Webpack 配置如下所示:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NodemonPlugin = require('nodemon-webpack-plugin');
require('file-loader')

module.exports = {
  mode: process.env.NODE_ENV || 'production',
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.(png|jpe?g|gif)$/i,
        use: ['file-loader'],
      },
      {
        test: /\.css$/i,
        use: ["style-loader"],
      }
    ],
  },
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin(),
    new NodemonPlugin()
  ]
};

Looks like you missed css-loader which is the key thing to process css file.看起来你错过了css-loader ,这是处理css文件的关键。 Using only style-loader is not enough since style-loader is all about to inject your css to the document.仅使用style-loader是不够的,因为style-loader即将将您的 css 注入到文档中。

So install & add to the configuration file:所以安装并添加到配置文件:

// install
// npm i -D css-loader

// Add it to the current css rule

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

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

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