【问题标题】:Error loading css file in webpack在 webpack 中加载 css 文件时出错
【发布时间】:2018-10-01 17:13:59
【问题描述】:

我正在尝试使用 webpack 加载 css 文件,但我不断收到此错误消息,如图所示。

我做了很多搜索,所以请不要,所有问题似乎都不适合我的情况。

以下是正在使用的各种文件

package.json

{
  "name": "loading_files",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "compile": "webpack",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "css-loader": "^0.28.11",
    "lodash": "^4.17.5",
    "style-loader": "^0.21.0",
    "webpack": "^4.6.0",
    "webpack-cli": "^2.0.14"
   }
}

webpack.config.js

"use strict"

let path = require("path");

module.exports = {
  mode: "development",
  entry: "./src/index.js",

  output: {
    filename: 'bundler.js',
    path: path.resolve(__dirname, 'dist'),
  },
 module:{
   rules: [
            {
              test: "/\.css$/",
              use: ["style-loader", "css-loader"]
            }
         ]
       }
 }

index.js

import _ from 'lodash';
import css from './index.css';

function component() {
  var element = document.createElement('div');
  element.innerHTML = _.join(['Hello', 'webpack'], ' ');
  element.classList.add('hello');
  return element;
}

document.body.appendChild(component());

index.css

.hello{
  color: red;


 }

我目前正在使用webpack v4.6.0npm v5.0.0

【问题讨论】:

    标签: css webpack webpack-style-loader css-loader


    【解决方案1】:

    在你的webpack.config.js

    请从regex 表达式中删除""

    // Whatever else you got here
    rules: [
        {
          test: /\.css$/,
          use: ["style-loader", "css-loader"]
        }
    ]
    

    【讨论】:

    • 非常感谢@Ru,那么为什么它不能与“/\.css$/”一起使用??
    • 嗨@lilfancy 正则表达式不适用于""。我相信"" 会导致正则表达式变成字符串而不是正则表达式。
    【解决方案2】:

    您的 webpack 配置文件不应具有文件扩展名 .json。 请将扩展名改为.js

    另外,你需要告诉 webpack,你想使用一个配置文件并给它这个文件的路径。在您的 package.json 中,请修改以下属性:

    {
       scripts: {
          "compile": "webpack --config webpack.config.js",
       }
    }
    

    【讨论】:

    • 感谢您的回复,我会进行更正并回复您@Daniel
    猜你喜欢
    • 1970-01-01
    • 2018-07-04
    • 2016-03-30
    • 2023-03-14
    • 1970-01-01
    • 2020-10-23
    • 2017-05-21
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多