无法将 CSS 文件导入 React 项目 [英] Cant Import CSS files into React Project

查看:21
本文介绍了无法将 CSS 文件导入 React 项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when i tried to import css file it showed error that loaders are missing. so i have installed css-loader and style-loader packages. if i add those packages to webpack.config.js i get following error. i dont know how to resolve it.

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 修改为此并将您的 css 文件导入到您的 App 组件中,如下所示 import './file.css';(假设css文件和你的App组件在同一个目录下)

Modifie your webpack.config.js to this and import your css file on your App component like this import './file.css'; (assuming that the css file is in the same directory as your App component)

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 文件导入 React 项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆