【发布时间】:2016-10-26 02:18:32
【问题描述】:
我正在尝试使用“className”元素更改 ReactJS 中按钮的样式。但是,我在 WebStorm 中收到一条错误消息,指出“未解析的变量 nameOfClass”,当我运行 webpack 并在 localhost 上打开页面时,没有进行样式更改。我尝试了不同的方法来导入 CSS 文件和命名约定,但都无济于事。
React Component 类的文件在这里:
import * as React from "react";
var styles = require('./Roster.css');
export class Roster extends React.Component<{},{}> {
render() {
return (
<div>
<button className={styles.nameOfClass} type="button" >Players</button>
</div>
);
}
}
Roster.css 文件在这里:
.nameOfClass {
background-color: #ff0000;
}
webpack.config.js
var ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
entry: "./src/index.tsx",
output: {
filename: "./dist/bundle.js",
},
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
externals: ['axios'],
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: ["", ".webpack.js", ".web.js", ".ts", ".tsx", ".js"]
},
module: {
loaders: [
// All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
{ test: /\.tsx?$/,
loader: "ts-loader"
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'),
}
],
preLoaders: [
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{ test: /\.js$/, loader: "source-map-loader" }
]
},
plugins: [
new ExtractTextPlugin('styles.css', { allChunks: true })
],
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
},
};
【问题讨论】:
-
你在 webpack 中使用了 CSS 加载器吗?
-
是的,我编辑了我的帖子以包含 webpack.config.js
-
它看起来像 Webstorm 中的一个错误。我正在使用 css-modules 并且当我添加类并导入它们时也收到这些警告,但是样式正确呈现并且 eslint 和 stylelint 很好。
标签: css reactjs typescript