无法将 CSS 个文件导入 React 项目

Cant Import CSS files into React Project

当我尝试导入 css 文件时,它显示加载程序丢失的错误。所以我安装了 css-loader 和 style-loader 包。如果我将这些包添加到 webpack.config.js 我会收到以下错误。不知道怎么解决。

ERROR in ./node_modules/css-loader!./src/index.js
Module build failed: Unknown word (1:1)

> 1 | import React from 'react';
    | ^
  2 | import ReactDOM from 'react-dom';
  3 | import {App} from './components/App';
  4 |

  @ ./src/index.js 3:14-73
  @ multi (webpack)-dev-server/client?http://localhost:8080 
  ./src/index.js

Webpack.config.js

module.exports = {
entry: [
  './src/index.js'
],
module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ["babel-loader","style-loader","css-loader"],            
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
output: {
  path: __dirname + '/dist',
  publicPath: '/',
  filename: 'bundle.js'
},
devServer: {
  contentBase: './dist'
}
};

我已经安装了以下依赖项

package.json

{
 "name": "Reactjs",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "scripts": {
 "start": "webpack-dev-server --config ./webpack.config.js --mode 
 development"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "babel": {
 "presets": [
  "env",
  "react",
  "stage-2"
 ]
 },
 "devDependencies": {
 "babel-core": "^6.26.0",
 "babel-loader": "^7.1.4",
 "babel-preset-env": "^1.6.1",
 "babel-preset-react": "^6.24.1",
 "babel-preset-stage-2": "^6.24.1",
 "css-loader": "^0.28.11",
 "style-loader": "^0.20.3",
 "webpack": "^4.2.0",
 "webpack-cli": "^2.0.12",
 "webpack-dev-server": "^3.1.1"
 },
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-router-dom": "^4.2.2"
 }
 }

将你的 webpack.config.js 修改为这个并在你的 App 组件上导入你的 css 文件,就像这样 import './file.css'; (假设 css 文件与你的 App 组件)

module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ["babel-loader"],            
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      }
    ]
  },

  resolve: {
    extensions: ['*', '.js', '.jsx']
  },
output: {
  path: __dirname + '/dist',
  publicPath: '/',
  filename: 'bundle.js'
},
devServer: {
  contentBase: './dist'
}
};

您需要为 css 添加一个单独的规则到您的 webpack.config 以便将 css 加载到您的项目中。

... rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ["babel-loader"] }, { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] ...

您正在使用 style-loadercss-loader 转换您的 .jsx 文件,这将引发错误。