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

xiaoxiao2021-02-28  7

 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';
转载请注明原文地址: https://www.6miu.com/read-2349990.html

最新回复(0)