无法在 .tsx 文件中导入 CSS 模块

Posted

技术标签:

【中文标题】无法在 .tsx 文件中导入 CSS 模块【英文标题】:Cannot import CSS module in .tsx file 【发布时间】:2019-05-26 11:55:20 【问题描述】:

我正在使用 typescript 构建基本的反应应用程序,但我无法在 index.tsx 文件中导入 CSS 文件

我可以通过以下方式导入 index.css 文件:

import './index.css'; 
//this import gives typescript error when running webpack 

但无法导入为

import * as Styles from './index.css';

这是我的 webpack.config.js 文件

var path = require("path");
var htmlWebpackPlugin = require('html-webpack-plugin')
var config = 
    mode:"none",
    entry:"./src/index.tsx",
    output:
        path: path.resolve(__dirname,"dist"),
        filename: "bundle.js"
    ,
    resolve:
        extensions:[".ts", ".tsx", ".js"]
    ,
    module:
        rules:[
            test:/\.tsx?$/, loader:"awesome-typescript-loader",
             test: /\.css$/, include: path.join(__dirname, 'src/'),
             loader:"typings-for-css-modules-loader" 
        ]
    ,
    plugins:[new HtmlWebpackPlugin(
        template: './index.html'
    )]
;

module.exports = config;

我在发布之前尝试了以下链接,但没有成功

How to include .css file in .tsx typescript?

How to import css file for into Component .jsx file

https://github.com/parcel-bundler/parcel/issues/616

提前致谢

【问题讨论】:

我编辑了代码 sn-ps ..抱歉代码错误 就我而言,它工作正常,但给出 tslint 错误“找不到模块 ./index.css”。我尝试从https://github.com/zeit/styled-jsx tslint 搜索扩展名为 .ts 的文件,因此在您的情况下,tslint 可能无法找到 index.css.ts 文件,因此它会抛出错误“找不到模块” 我的 CSS 文件的扩展名为 .css,而不是 .css.ts。比如:index.css TypeScript 不知道除了.ts.tsx 之外的文件,因此如果导入的文件后缀未知,它将引发错误。如果你的 webpack 配置允许你导入其他类型的文件,你必须告诉 TypeScript 编译器这些文件存在 【参考方案1】:

使用新版本的 React,要使用 CSS 模块,您无需在 Webpack 中配置任何内容或拒绝您的项目。 您需要做的就是:

    安装css-modules-loader:https://github.com/gajus/react-css-modules 将文件名styles.css改为styles.module.css

    将 css 文件导入到您的组件中:

    import styles from './styles.module.css'

    在组件中使用className:

    <div className=styles.app> Hello World </div>

演示项目:https://codesandbox.io/s/kwyr5p378o

【讨论】:

我尝试了上述方法,但我收到以下错误You may need an appropriate loader to handle this file type. > .foo | color: chocolate; | @ ./src/components/index.tsx 6:15-45 在此之后我尝试使用 css-loader 并且代码存在于最终 bundle.js 文件中但样式不是应用于组件 当我在 html 中明确链接 CSS 文件时,此方法有效 我没有使用 create-react-app 模板。我正在从头开始构建,没有初始配置【参考方案2】:

typings-for-css-modules-loaderdocs,建议你将css导入为

要么

import styles from './index.css';

import * as styles from './index.css';

在您的示例中,您缺少关键字 from

【讨论】:

以上是关于无法在 .tsx 文件中导入 CSS 模块的主要内容,如果未能解决你的问题,请参考以下文章

使用 css 模块,如何从文件中导入类

在 Angular 中导入全局 css 文件会导致 Webpack 发出巨大的模块包

如何在 React 组件中导入 CSS 文件

在 tsx 编译错误中导入 jsx 文件

无法在 Python 中导入位置设置为 PYTHONPATH 的模块

无法在nodejs中导入带有require()的模块