无法将CSS文件导入React Project

时间:2018-03-22 09:52:11

标签: reactjs webpack webpack-style-loader

当我尝试导入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"
 }
 }

2 个答案:

答案 0 :(得分: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'
}
};

答案 1 :(得分:1)

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

style-loader

您正在使用css-loader.jsx转换将导致错误的var hive = Registry.LocalMachine; var keys = hive.OpenSubKey("SOFTWARE") ?.OpenSubKey("Microsoft") ?.OpenSubKey("Windows") ?.OpenSubKey("CurrentVersion") ?.OpenSubKey("MMDevices") ?.OpenSubKey("Audio")?.GetSubKeyNames(); 个文件。