-->

Cant Import CSS files into React Project

2019-05-23 18:51发布

问题:

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'
}
};

i have installed following dependecies

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"
 }
 }

回答1:

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'
}
};


回答2:

You need to add a separate rule for css to your webpack.config in order to load css into your project.

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

You're using style-loader and css-loader to transform your .jsx files which is going to throw an error.