【问题标题】:'Module parse failed: Unexpected token' when adding css file to React App将 css 文件添加到 React App 时出现“模块解析失败:意外的令牌”
【发布时间】:2021-06-09 20:15:35
【问题描述】:

在将 css 文件导入 index.js 后立即在浏览器中弹出此错误。我尝试将不同样式的加载器输入到 webpack.config.js 文件中,但没有成功。这是css:

h1 {
    color: red;
}

我已经导入了:

import './App.css'

这里是 webpack 文件:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, 'src', 'index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          presets: ["@babel/preset-env", "@babel/preset-react"]
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') })]
};

【问题讨论】:

    标签: javascript css reactjs webpack


    【解决方案1】:

    您的 Webpack 配置目前似乎不包含有关如何编译 CSS 文件的任何规则。你可以通过以下方式配置 Webpack:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader'],
          },
        ],
      },
    };
    
    

    所以在你的具体例子中,它会是这样的:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      mode: 'development',
      entry: path.resolve(__dirname, 'src', 'index.js'),
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js'
      },
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
            options: {
              presets: ["@babel/preset-env", "@babel/preset-react"]
            }
          },
          {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader'],
          },
        ]
      },
      plugins: [new HtmlWebpackPlugin({ template: path.resolve(__dirname, 'src', 'index.html') })]
    };
    

    有关样式加载器的更多详细信息,请访问他们的documentation.

    【讨论】:

    • 伙计,我已经尝试过了,不幸的是仍然得到相同的响应。我也按照您发送的链接中的步骤进行操作。感谢您回复我
    • 您是否仍然收到相同的错误消息?
    • 不幸的是,我愿意
    • 如果您可以使用您当前的代码创建一个代码框,那么我可以更详细地查看它以重现它。
    猜你喜欢
    • 1970-01-01
    • 2019-04-18
    • 2021-05-01
    • 2023-01-12
    • 2021-11-29
    • 1970-01-01
    • 2019-02-15
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多