16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptを導入してCSSをimportできるようにする

Posted at

はじめに

これまでES6で書いてきたプロジェクトにTypeScriptを導入した際に、
cssがimportできなかったのでメモとして。

TypeScriptでCSS Moduleを使用できるようにする

TypeScriptではCSSやSASSファイルをこれまで通りimportするとエラーが出る。
そこで、CSSファイルごとに型の定義ファイルを作成することでimportできるようにする。

手順1: 型定義ファイルを作成する

作成したCSSファイルと同じ階層にCSSファイルと同じ名前.css.d.tsを作成する。
例)style.cssを作成した場合、style.css.d.tsを作成する。

src
 ¦-- style.css
 ¦-- style.css.d.ts

手順2: 型を定義する

型定義ファイルにCSSに対応する型を記述する。
以下のようなCSSを記述したとする。

style.css
.wrapper {
  border-left: 1px solid #eee;
}
.messages {
  padding: 15px;
}

その場合の型定義ファイルは以下のようになる。

style.css.d.ts
export const wrapper: string
export const messages: string

手順3: TSファイルでimportする

CSSファイルをimportできるようになっているので、TSファイルimportする。

import * as styles from 'style'

手順4: 使用する

あとはclassNameなどで使用するだけ。

<div className={styles.wrapper}>
...
</div>

おわりに

これでCSSは読み込めるようになった。
SASSだとまた違うようなので、どうしたらSASS(SCSS)を使えるようになるのか調べたい。
ちらっとドキュメントに書いてあったような。

間違いがありましたらコメントなどでご指摘ください。
こういう方法もあるよというコメントも大歓迎です。

16
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?