7
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.

webpack4 + TypeScript + React CSS Modules

Last updated at Posted at 2018-04-01

最近TypeScriptを本格的に導入し始めたんですが webpack + ES201X + React CSS Modules な環境をTypeScriptでも導入したかったので備忘の意味も込めて残しておきます。

やりたいこと

  • TSXで書くReactコンポーネントにCSS Modulesを利用したい
  • このためだけにBabelをインストールしたくない
  • Autoprefixer欲しい

環境

  • TypeScript 2.8.1
  • webpack 4.4.1
  • React CSS Modules 4.7.2
  • CSSは今回はPostCSSを利用(Sassでもいいけどお好みで)

設定

tsconfig.json(一部)

{
  "compilerOptions": {
    ...
    // デコレータを使用するため true にする
    "experimentalDecorators": true,
    // React指定
    "jsx": "react",
    // 型定義ファイルを作るのでディレクトリを指定
    "typeRoots": [
      "typings",
      "node_modules/@types"
    ]
  },
  ...
}

webpack.config.ts(一部)

const config: webpack.Configuration = {
  ...
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        use: 'awesome-typescript-loader'
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        use: [
          'style-loader',
          'css-loader?modules&importLoaders=1&localIdentName=[name]--[local]--[hash:base64:5]',
          {
            loader: 'postcss-loader',
            options: {
              sourceMap: true,
              plugins: [
                autoprefixer()
              ]
            }
          }
        ]
      }
    ]
  },
  ...
};

export default config;

型定義ファイル


declare module "*.css" {
  const classes: {[className: string]: string}
  export default classes
}

使用例

CSS


.title {
  color: blue;
}

React


import * as React from 'react';
import * as CSSModules from 'react-css-modules';
import * as styles from 'style.css';

@CSSModules(styles)
export default class Component extends React.Component {
  render(): JSX.Element {
    return (
      <div>
        <h1 styleName="title">Hello World</h1>
      </div>
    );
  }
}

webpack3でも同じ感じで使えるはず。

ソース

7
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
7
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?