【问题标题】:Webpack 4.6.0 loading css file: You may need an appropriate loader to handle this file typeWebpack 4.6.0 加载 css 文件:您可能需要适当的加载器来处理此文件类型
【发布时间】:2018-04-24 04:32:09
【问题描述】:

我一直在使用 webpack 4.6.0:

编译时遇到以下问题:

Uncaught Error: Module parse failed: Unexpected token (1:4)
You may need an appropriate loader to handle this file type.
| div {
|     background-color: yellow;
|     color: red;

我的 webpck 配置如下:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  mode:'development',
  entry: './src/code/app.js',
  output: { path: __dirname, filename: 'bundle.js'},
  watch: true,

  module: {
    rules: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          plugins: "transform-class-properties",
          presets: ['es2015', 'react']
        }
      },
      {
        // Do not transform vendor's CSS with CSS-modules
        // The point is that they remain in global scope.
        // Since we require these CSS files in our JS or CSS files,
        // they will be a part of our compilation either way.
        // So, no need for ExtractTextPlugin here.
        test: /\.css$/,
        include: /node_modules/,
        loader: 'css-loader'
      }
    ]
  }
};

我有:

"css-loader": "^0.28.11",

我的文件结构是这样的:

root:
-src
 |-code
   |-XXXX.js
 |-css
   |-HomePage.css

我认为这与我的css加载器有关,我在网上尝试了很多方法,但都没有奏效。有什么与我的文件结构有关的东西吗?

【问题讨论】:

    标签: css reactjs webpack


    【解决方案1】:

    我相信您仍然需要为自己的css 文件添加规则。尝试将此添加到您的规则中。

    {
      // Preprocess your css files
      // you can add additional loaders here (e.g. sass/less etc.)
      test: /\.css$/,
      exclude: /node_modules/,
      use: ['style-loader', 'css-loader'],
    }
    

    【讨论】:

    • 我想我已经在配置文件中有一个 .css 加载器设置。但无论如何,我已在“规则”部分附加了您的答案。我仍然面临同样的问题
    • 该规则适用于供应商文件,请注意该对象中的键是include: /node_modules/。在该规则中,您能否将use 的值更改为与我在回答@weidu 中给您的示例相同?即use: ['style-loader', 'css-loader']
    • 实际上,查看 css-loader 存储库,您似乎只需使用 { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } 就可以让它工作
    • 哦,谢谢,现在我明白您所说的供应商文件是什么意思了。效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2019-07-26
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多