"未解决的变量"当使用className = {styles.nameOfClass}时

时间:2016-06-23 16:13:51

标签: css reactjs typescript

我正在尝试使用" className"在ReactJS中更改按钮的样式。元件。但是,我收到一条错误,说明"未解决的变量nameOfClass"在WebStorm中,当我运行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"
    },
};

2 个答案:

答案 0 :(得分:0)

应该看起来像:

import * as React from "react";

export class Roster extends React.Component<{},{}> {
    render() {
        return <div>
            <button className="nameOfClass" type="button">Players</button>
        </div>
    }
}

您不能要求使用css文件,只需要打字稿/ javascript文件。

css-modules的东西,并且有一些针对react / css的js解决方案,例如RadiumreactCss

答案 1 :(得分:0)

您不必要求样式文件。

import * as React from "react";

export class Roster extends React.Component<{},{}> {

    render() {
        return (
            <div>
                <button className="nameOfClass" type="button" >Players</button>
            </div>
        );
    }
}

和你的css文件:

.nameOfClass {
    background-color: #ff0000;
}