在 React 组件中使用由 webpack 构建的 Typescript 的 CSS 模块 [英] Use CSS Modules in React components with Typescript built by webpack

查看:21
本文介绍了在 React 组件中使用由 webpack 构建的 Typescript 的 CSS 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在用 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");模块.出口={条目:['./src/main.tsx'],输出: {路径:path.resolve(__dirname, "target"),publicPath: "/assets/",文件名:'bundle.js'},调试:真的,开发工具:'评估源地图',插件: [新的 webpack.optimize.DedupePlugin(),新的 webpack.optimize.UglifyJsPlugin({minimize: true})],解决: {扩展名:['', '.jsx', '.ts', '.js', '.tsx', '.css', '.less']},模块: {装载机: [{测试:/.ts$/,装载机:'ts-装载机'},{测试:/.tsx$/,loader: 'react-hot!ts-loader'}, {测试:/.jsx$/,排除:/(node_modules|bower_components)/,loader: "react-hot!babel-loader"},{测试:/.js$/,排除:/(node_modules|bower_components)/,装载机:巴贝尔装载机"}, {测试:/.css/,排除:/(node_modules|bower_components)/,loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader')}]},插件: [new ExtractTextPlugin("styles.css", {allChunks: true})],postcss:函数(){返回 [require("postcss-cssnext")()]}}

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

import React = require('react');导入样式 = 要求('../../../css/tree.css')类 Tree 扩展了 React.Component<{}, TreeState>{...使成为() {var 组件 = this.state.components返回 (<div><h3 className={styles.h3} >组件</h3><div id="tree" className="list-group">...

)}}出口 = 树

tree.css

.h3{红色;}

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

<块引用>

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

在运行时和

<块引用>

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

由 TS 编译器提供.发生了什么?在我看来 css-loader 甚至没有发出 ICSS?还是 ts-loader 的行为有问题?

解决方案

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

var 样式 = require('../../../css/tree.css')`

I want to use the css-loader with the 'modules' option of webpack in a React application written in Typescript. This example was my starting point (they are using Babel, webpack and React).

webpack config

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")()]
    }
}

This is a React component I want to style with an accompanying CSS file:

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

tree.css

.h3{
    color: red;
}

No matter what I'm doing (tried changing the import syntax, tried declaring the 'require' for ts-loader, described here, I always get:

Uncaught Error: Cannot find module "../../../css/tree.css"

at runtime and

error TS2307: Cannot find module '../../../css/tree.css'.

by the TS compiler. Whats happening? Seems to me that css-loader is not even emitting ICSS? Or is it ts-loader behaving wrong?

解决方案

import has special meaning to TypeScript. It means that TypeScript will attempt to load and understand the thing being imported. The right way is to define require like you mentioned but then var instead of import:

var styles = require('../../../css/tree.css')`

这篇关于在 React 组件中使用由 webpack 构建的 Typescript 的 CSS 模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆