Addng css files in React project with Webpack 4

2019-08-18 04:45发布

问题:

I am building a simple React app from scratch using Webpack. I was finally able to run the dev server and when I tried to apply some styles via CSS, the files wouldn't load and I assume my Webpack 4 configuration is not right.

Here is the code:

webpack.config.js

// const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const path = require('path');


module.exports = {
    mode: 'development',
    entry: ['./src/index.js'],
    resolve: {
        extensions: [".js", ".jsx"]
    },
    output: {
      filename: 'main.js',
      path: path.resolve(__dirname, 'dist'),
      publicPath: '/dist',
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        compress: true,
        port: 8080
    },
    module: {
        rules: [
            {
                test: /\.js|.jsx$/,
                exclude: /node_modules/,
                loader: "babel-loader",
                options: {
                    presets: ["react"]
                }

            },
            {
                test: /\.css$/,
                use: ["style-loader", "css-loader"]
            },
            {
                test: /\.(png|jpg)$/,
                loader: 'url-loader'
            }
        ]
    },

};

My project structure is like this, I will include only src because it lives in the root:

 **src**
      |_assets
      |_componentns
      |_styles
        |_App.css
        |_index.css
      App.jsx
      index.js
      index.html

I would like to be able to add multiple css files for each component I have and apply them, and to be able to style the index the index.html. Thank you very much for your help.

回答1:

All you have to do is import the CSS files when needed as you would a JavaScript model. So if you want to have a style sheet for you whole application, you can import a global stylesheet in your index.js.

import './styles/index.css';

and you can do the same for each component with specific styles

import './styles/App.css'

in which case you might want to setup CSS modules to avoid overlapping class names.



回答2:

Your webpack configuration looks fine. make sure you import the required css files in your components.

import "./App.css";

class App extends Component {
  render() {
    return (
      <div>
        <Child />
      </div>
    );
  }
}


回答3:

Ok, rookie mistake here, the way I ahve set up webpack is I have to build it first and then run the dev server, no the other way around. All answers above are valid and helpful, I just forgot to run build after changes.