【问题标题】:webpack and react recognise css class nameswebpack 和 react 识别 css 类名
【发布时间】:2018-01-08 02:46:48
【问题描述】:

我有一个 React 组件,我正在尝试导入 css。

import './Example.css';

class Example extends Component {
  return <div className="example-class">Example</div>
}

我的文件结构是这样的

build
  -index.js
src
  -index.js
  -Example.css

我的webpack.config.js 如下所示。

目前一切都在构建,但 css 似乎没有被拾取。

谁能看到我需要做什么才能在构建后访问我的类名?

var path = require('path');
module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'index.js',
    libraryTarget: 'commonjs2'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: path.resolve(__dirname, 'src'),
        exclude: /(node_modules|bower_components|build)/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['env']
          }
        }
    },
    {
      test: /\.css$/,
      use: [ 'css-loader' ]
    }
    ]
  },
  externals: {
    'react': 'commonjs react'
  }
};

【问题讨论】:

  • 您是否遇到任何错误。目前发生了什么
  • @ShubhamKhatri 它不识别 css
  • 你的css文件在哪个文件夹中
  • @ShubhamKhatri 更新了问题
  • 能否尝试在webpack代码中添加context: path.resolve(__dirname, 'src')

标签: javascript reactjs webpack ecmascript-6


【解决方案1】:

css-loader 仅处理 CSS,但不使其在浏览器中可用。您可以为此使用style-loader,它将CSS 注入&lt;style&gt; 标记。 (另见Loading CSS

{
  test: /\.css$/,
  use: [ 'style-loader', 'css-loader' ]
}

另一种可能性是使用extract-text-webpack-plugin 提取CSS。除了您的 JavaScript 包之外,它还将提取 CSS 并创建一个 .css 文件。然后,您可以在 HTML 中包含 CSS。

【讨论】:

【解决方案2】:

你可以试试这个:

import styles from './Example.css';

class Example extends Component {
  return <div className={styles.example-class}>Example</div>
}

【讨论】:

  • 我认为- 有问题
猜你喜欢
  • 2018-08-12
  • 2019-01-16
  • 2018-11-03
  • 2016-05-16
  • 2019-11-14
  • 2018-11-19
  • 2016-11-06
  • 2020-08-27
  • 2017-07-24
相关资源
最近更新 更多