Typescript引入css文件时,找不到css模块

 typescript比较适合大型的项目,所以为了就开始自学typescript,遇到的问题还是挺多的,遇到了

“Typescript引入css文件时,找不到css模块”,郁闷了好久,最好翻墙出去找到了解决的方案,英文比较简单,我就不去卖弄自己的翻译了,亲测好使。希望可以帮助到同样有问题的朋友。如果有解决不了的朋友,可以留言,愿尽力帮忙。

Using CSS Modules with TypeScript is not as obvious as with JavaScript. The reason is that TypeScript has special treatment for imports and if you try to use CSS Modules the same way you did in JavaScript:

import s from './Button.css';

You’ll get an error: “Cannot find module ‘./Button.css’”. There are several ways to fix that.

The easy way

You can bypass TypeScript import magic by using require instead of import:

const s = require('./Button.css');

It’s processed by webpack as usual but you won’t have type check and autocomplete for CSS class names.

The better way

To use import you need typings for CSS. For example, you have Button.csslike this:

.foo {
  color: chocolate;
}
.barBaz {
  color: tomato;
}

Now you need Button.css.d.ts like this:

export const foo: string;
export const barBaz: string;

typings-for-css-modules-loader is a drop-in replacement for css-loader that generates typings for CSS on the fly. Let’s install it:

npm install --save-dev typings-for-css-modules-loader

Then update your webpack config:

module: {
  rules: [
    {
      test: /\.css$/,
      include: path.join(__dirname, 'src/components'),
      use: [
        'style-loader',
        {
          loader: 'typings-for-css-modules-loader',
          options: {
            modules: true,
            namedExport: true
          }
        }
      ]
    }
  ]
}

Now you can import styles like this:

import * as s from './Button.css';
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值