Learn React with TypeScript3を読んでる 環境構築とかその他の手直しが必要だった箇所について

2020年02月29日 00時02分

Learn React with TypeScript 3を読み進めていきましたが、環境構築の部分で結構躓いたので備忘録的なまとめ。

基本的には公式サイトが一番参考になる…。

TypeScript -React & Webpack

Webpack – TypeScript

ts-loader

webpack まわり

resolve 内に Modules を追加

'modules: ["src", "node_modules"]'

背景

webpack のサーバーを起動しようとすると、


ERROR in (webpack)-dev-server/client?http://localhost:9000

Module not found: Error: Can't resolve './overlay' in

みたいなエラーが出る時に有効

各種 loader の追加

css(style-loader, css-loader)とsvgを追加した。module も追加が必要です。

  {

      test: /\.css$/i,

      use: ['style-loader', 'css-loader'],

    },
  {
      test: /\.svg$/,
      loader: 'svg-inline-loader'
  }

背景

css をインポートしたいってなった時にエラーが出たので…

//webpack.config.json
const path = require("path");
module.exports = {
	entry: "./src/index.tsx",
    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",
	output: {
		path: path.resolve(__dirname, "dist"),
		filename: "bundle.js"
	  },
    resolve: {
		modules: ["src", "node_modules"],
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".js",".ts", ".tsx"]
    },

    module: {
        rules: [
            {
                test: /\.ts(x?)$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: "ts-loader"
                    }
                ]
            },
            {
                enforce: "pre",
                test: /\.js$/,
                loader: "source-map-loader"
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
              },
            {
                test: /\.svg$/,
                loader: 'svg-inline-loader'
            }
        ]
    },
	devServer: {
		contentBase: path.join(__dirname, "dist"),
		compress: true,
		port: 9000
	  }
};

import 関係

tsconfig.json 内の allowSyntheticDefaultImports を true にするかどうかで変わってくる感じですね。

コンパイラに怒られるので、default を避けるか、名前付きインポートを行う。

import MDN

// tsconfig.json
{
  "compilerOptions": {
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
      "allowSyntheticDefaultImports":true,
      "outDir": "./dist/",
      "sourceMap": true,
      "noImplicitAny": true,
      "module": "es6",
      "target": "es6",
      "jsx": "react"
  }
}

CSS 関係

ポップアップ上にボタンを作る実装部分があるのですが本のまま書くと、visibility:hidden にしている要素が残っていてポップアップ下の要素がクリックできないので、desplay:none にする必要がありました。

React 楽しい

React も独自の型を設定しつつ実装を行っていきますが、型を定義できる TypeScript のいい点ととてもマッチしていると思います。

お互いの強みを活かしつつコンポーネントごとに実装していけるので楽しいですね。

もうちょっと読み進めていきたいと思います。