【问题标题】:How to load css in react app?如何在反应应用程序中加载css?
【发布时间】:2018-02-05 19:30:09
【问题描述】:

我使用 create-react-app 创建了一个 react 应用程序,一切正常,只是我不知道如何加载 css/stylus 文件。

在我之前没有使用 create-react-app 创建的 react 项目中,我使用了 webpack.config,但现在我不知道在哪里包含该文件以及如何使用它。

这是我的文件夹结构:

.  
+--client  
|  +--node_modules
|  +--public
|  +--src
|  +--package.json
+--server
|  +--node_modules
|  +--src
|  +--.babelrc
|  +--package.json

这是我之前的webpack.config.dev.js文件:

import path from 'path';
import webpack from 'webpack';

export default {
  entry: [
    'webpack-hot-middleware/client?reload=true',
    path.join(__dirname, '/client/index.js')
  ],
  output: {
    filename: 'bundle.js',
    path: '/',
    publicPath: '/'
  },
  plugins: [
    new webpack.NoEmitOnErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.join(__dirname, 'client'),
        loader: 'babel-loader',
      },
      {
        test: /\.styl$/,
        use: [
          'style-loader',
          'css-loader',
          {
            loader: 'stylus-loader',
          },
        ],
      },
      {
        test: /\.css?$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: [ '.js', '.styl' ]
  }
}

如果我需要提供更多信息,请告诉我。

【问题讨论】:

    标签: css node.js reactjs webpack


    【解决方案1】:

    在他们的文档中有关于如何将 SCSS 和 Less 文件添加到 create-react-app 项目的详细信息。详情请查看here

    您只需导入如下所示的文件即可添加基本的 CSS 样式;

    import '/css/main.css';
    

    或者您可以添加为classNames

    const styles = {
       header: {
         fontSize: 18,
         color: '#909090',
       }
     };
    
     export default class Header extends React.Component {
       render() {
         return (
           <h1 className={styles.header}>This is a header</h1>
         );
       }
     }
    

    【讨论】:

      【解决方案2】:

      其中一种方法是从 JS 文件中加载 CSS 文件(通过 css-loader),用于 Text.jsx

      import React from 'react';
      import './screen.css'; // if screen.css is located next to Text.jsx
      
      class Text extends React.Component {
        // ...
      }
      
      export default Text;
      

      您还可以生成输出 CSS,例如使用ExtractTextPlugin(见Webpack2 loading and extracting LESS file

      【讨论】:

        猜你喜欢
        • 2012-01-15
        • 2017-09-11
        • 2018-03-18
        • 1970-01-01
        • 2020-05-06
        • 2014-05-16
        • 2019-05-16
        • 1970-01-01
        • 2019-04-19
        相关资源
        最近更新 更多