[英]webpack and react recognise css class names
I have a React component that I am trying to import the css. 我有一个React组件,我正在尝试导入CSS。
import './Example.css';
class Example extends Component {
return <div className="example-class">Example</div>
}
My file structure looks like this 我的文件结构如下所示
build
-index.js
src
-index.js
-Example.css
My webpack.config.js
looks like the following. 我的
webpack.config.js
如下所示。
Currently everything builds, but the css doesnt appear to be getting picked up. 当前所有东西都建立了,但是css似乎没有被拾取。
Can anyone see what I would need to do to access my classnames after build? 任何人都可以看到构建后访问我的类名需要做什么吗?
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'
}
};
The css-loader
only processes the CSS but does not make it available in the browser. css-loader
仅处理CSS,但无法在浏览器中使用。 You can use style-loader
for this, which injects the CSS into a <style>
tag. 您可以为此使用
style-loader
,它将CSS注入<style>
标记中。 (see also Loading CSS ) (另请参阅加载CSS )
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
Another possibility is to extract the CSS with extract-text-webpack-plugin
. 另一种可能性是使用
extract-text-webpack-plugin
提取CSS。 It will extract the CSS and create a .css
file in addition to your JavaScript bundle. 除了JavaScript包之外,它还将提取CSS并创建一个
.css
文件。 You can then include the CSS in your HTML. 然后,您可以将CSS包含在HTML中。
You can try this: 您可以尝试以下方法:
import styles from './Example.css';
class Example extends Component {
return <div className={styles.example-class}>Example</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.