3
2

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 + React + WebpackでCSSを使う

Last updated at Posted at 2020-03-11
  1. css-loaderとstyle-loaderパッケージをインストール

    $ npm install style-loader css-loader --save-dev
    
  2. webpack.configにcssのためのルールを追加。

    ...
    rules: [
      ...
      { test: /\.css$/, loader: ['style-loader', 'css-loader'] }, # この行を追加。
    

上の様に書くと、*.cssのファイルが、入力 -> css-loader -> style-loader -> 出力の形で処理される。
css-loaderが入力のcssファイルの@importurl()を解決して一つにまとめたものを、style-loaderが、以下のようにstyleタグの中に入れて、出力先のhtmlのheadタグ中に挿入する。

```html
<head>
  <style type="text/css">
    #gigantic {
      font-size: 1000px;
    }
  </style>
  ...
````
  1. cssファイルを用意して、srcの下あたりに置く。例えばstyles.cssを以下の内容で作る。

    #gigantic {
      font-size: 1000px;
    }
    
    .crazy-small {
      font-size: 2px;
    }
    
  2. cssを使いたいコンポーネント(例えば、app.tsx)で、cssファイルをインポートして、webpackに、このコンポーネントのHTMLにCSSを挿入するよう指示する。相対パスはモジュールと同じ形で指定すればOK。

    import "../../css/styles.css"
    
  3. HTMLにStyleがリンクされてる場合と同じように、idやclassでスタイルを適用する。

    <div id="gigantic">Tokyo</div>
    <div className="crazy-small">Olympic</div>
    
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?