LoginSignup
1
2

More than 5 years have passed since last update.

webpack + awesome-typescript-loader + react で開発環境を用意する

Last updated at Posted at 2019-01-12

※ この資料書いたときには awesome-typescript-loader 悪くないじゃんと思っていたんですが、2019年現在 ts-loaderです。


awesome-typescript-loaderTypescript 公式でも説明されているので採用。

タイトル通りのメモ。手軽に。

セットアップ

npm init -y
npm install --save react react-dom @types/react @types/react-dom
npm install --save-dev webpack webpack-dev-server webpack-cli
npm install --save-dev typescript awesome-typescript-loader source-map-loader
npm install --save-dev html-webpack-plugin

tsconfig.json

生成して

npx tsc --init

編集する

...

   "jsx": "react"

...

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CheckerPlugin } = require("awesome-typescript-loader");

module.exports = {
  entry: "./src/index.tsx",
  output: {
    filename: "bundle.js",
    path: __dirname + "/dist"
  },
  devtool: "source-map",
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".json"]
  },

  module: {
    rules: [
      { test: /\.tsx?$/, loader: "awesome-typescript-loader" },
      { enforce: "pre", test: /\.js$/, loader: "source-map-loader" }
    ]
  },
  devServer: {
    contentBase: path.join(__dirname, "public"),
    watchContentBase: true,
    open: true
  },
  optimization: {
    splitChunks: {
      chunks: "all"
    }
  },
  plugins: [
    new CheckerPlugin(),
    new HtmlWebpackPlugin({ template: "src/index.html" })
  ]
};

src/index.tsx

import * as React from "react";
import * as ReactDOM from "react-dom";

type Props = {
  greeting: string;
};

const Hello = (props: Props) => {
  return <h1>{props.greeting}</h1>;
};

ReactDOM.render(
  <Hello greeting="Hello World" />,
  document.querySelector("#content")
);

src/index.html

<div id="content"/>

package.json

{
  ... 

  "scripts": {
    "start": "webpack-dev-server --mode development",
    ...
  }

  ...
}

所感

es6 + babel + flowtype の環境よりビルドと型チェックが全体的に高速だったのが好印象でした。最近 flow がよく刺さるので typescript で安定かなぁという気分。

1
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
1
2