使用 Webpack 4 在 React 项目中添加 css 文件 [英] Addng css files in React project with Webpack 4

查看:29
本文介绍了使用 Webpack 4 在 React 项目中添加 css 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Webpack 从头开始​​构建一个简单的 React 应用程序.我终于能够运行开发服务器,当我尝试通过 CSS 应用一些样式时,文件无法加载,我认为我的 Webpack 4 配置不正确.

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.

代码如下:

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'
            }
        ]
    },

};

我的项目结构是这样的,我将只包含src,因为它位于根目录中:

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

我希望能够为我拥有的每个组件添加多个 css 文件并应用它们,并且能够将索引设置为 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.

推荐答案

您所要做的就是在需要时像导入 JavaScript 模块一样导入 CSS 文件.因此,如果您想为整个应用程序创建一个样式表,您可以在 index.js 中导入一个全局样式表.

All you have to do is import the CSS files when needed as you would a JavaScript module. So if you want to have a style sheet for your 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'

在这种情况下,您可能希望设置 CSS 模块 以避免重叠类名字.

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

这篇关于使用 Webpack 4 在 React 项目中添加 css 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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