在使用webpack构建的Typescript的React组件中使用CSS模块

Sha*_*ady 20 javascript typescript reactjs webpack react-css-modules

我想在一个用Typescript编写的React应用程序中使用带有webpack的'modules'选项的css-loader.这个例子是我的出发点(他们使用的是Babel,webpack和React).

webpack配置

var webpack=require('webpack');
var path=require('path');
var ExtractTextPlugin=require("extract-text-webpack-plugin");

module.exports={
    entry: ['./src/main.tsx'],
    output: {
        path: path.resolve(__dirname, "target"),
        publicPath: "/assets/",
        filename: 'bundle.js'
    },
    debug: true,
    devtool: 'eval-source-map',
    plugins: [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({minimize: true})
    ],
    resolve: {
        extensions: ['', '.jsx', '.ts', '.js', '.tsx', '.css', '.less']
    },
    module: {
        loaders: [
            {
                test: /\.ts$/,
                loader: 'ts-loader'
            },
            {
                test: /\.tsx$/,
                loader: 'react-hot!ts-loader'
            }, {
                test: /\.jsx$/,
                exclude: /(node_modules|bower_components)/,
                loader: "react-hot!babel-loader"
            },
            {
                test: /\.js$/,
                exclude: /(node_modules|bower_components)/,
                loader: "babel-loader"
            }, {
                test: /\.css/,
                exclude: /(node_modules|bower_components)/,
                loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader')
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin("styles.css", {allChunks: true})
    ],
    postcss: function() {
        return [require("postcss-cssnext")()]
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个React组件,我想用随附的CSS文件设置样式:

import React = require('react');
import styles = require('../../../css/tree.css')

class Tree extends React.Component<{}, TreeState> {
...

    render() {
        var components = this.state.components
        return (
            <div>
                <h3 className={styles.h3} >Components</h3>
                <div id="tree" className="list-group">
                    ...
                </div>
            </div>
        )
    }
}

    export = Tree
Run Code Online (Sandbox Code Playgroud)

tree.css

.h3{
    color: red;
}
Run Code Online (Sandbox Code Playgroud)

无论我在做什么(尝试更改导入语法,尝试声明ts-loader的'require',在这里描述,我总是得到:

未捕获错误:找不到模块"../../../css/tree.css"

在运行时和

错误TS2307:找不到模块'../../../css/tree.css'.

由TS编译器.发生了什么?在我看来,css-loader甚至没有发射ICSS?或者ts-loader行为错误?

Jam*_*tly 12

import对TypeScript有特殊意义.这意味着TypeScript将尝试加载和理解正在导入的内容.正确的方法是require像你提到的那样定义但var不是import:

var styles = require('../../../css/tree.css')`
Run Code Online (Sandbox Code Playgroud)


小智 8

  1. 根据ts-loader文档声明'require' .
  2. 使用'require'作为通用的<any>类型:require <any>("../../../ css/tree.css").

*.d.ts文件

declare var require: {
   <T>(path: string): T;
   (paths: string[], callback: (...modules: any[]) => void): void;
   ensure: (paths: string[], callback: (require: <T>(path: string) => T) => void) => void;
}; 
Run Code Online (Sandbox Code Playgroud)

*.tsx文件与组件

const styles = require<any>("../../../css/tree.css");
...
<h3 className={styles.h3}>Components</h3>
Run Code Online (Sandbox Code Playgroud)

我知道它已经回答了,但是在我意识到我需要使用泛型类型规范之前我已经挣扎了一段时间,但没有我无法访问CSS文件的内容.(我收到错误:类型'{}'上不存在属性'h3'.)