react-script-tsを使ってTypeScriptプロジェクトをビルド

2018-06-15T00:00:00+00:00 TypeScript

TypeScriptプロジェクトをreact-scripts-tsを使ってビルドする方法をメモ

※create-react-app使う前提では無いので注意

とりまぁ適当なReactアプリケーションをでっちあげるとこから。それをTypeScriptで記述していく

src/index.tsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { Hoge } from './Hoge';
import { Fuga } from './fuga';

class Main extends React.Component {
  render() {
    return (
      <div>
        <Hoge />
        <Fuga />
      </div>
    );
  }
}

ReactDOM.render(
    <Main />,
    document.querySelector('#app') as HTMLElement,
);

まぁ適当になんか画面に表示するようなのだけなので(ry

src/Hoge.tsx

import * as React from 'react';

export class Hoge extends React.Component {
  render() {
    return (
      <h2>hoge</h2>
    );
  }
}

src/fuga.js

import React from 'react';

export class Fuga extends React.Component {
  render() {
    return (
      <h2>fuga!</h2>
    );
  }
}

まぁこれでindex.tsxをコンパイルして使うのも同時にビルドしていきゃいいだけはずなんで、それをreact-scripts-tsでビルド出来るようにビルド環境を構築していく

必要なもの

public/index.html
package.json
tsconfig.json
tslint.json

を定義していく

※場合によっちゃwebpackとか入れてもいいんじゃないかと

3 public/index.html

<html>
  <body>
    <div id="app"></div>
  </body>
</html>

コンパイルしたTypeScriptからES5に返還されたのが<script>で注入される模様。例えば実際にビルドすると

<html>
  <body>
    <div id="app"></div>
    <script type="text/javascript" src="/static/js/main.02cbf82e.js"></script>
  </body>
</html>

てな感じになる模様

package.json

{
  "name": "sample",
  "version": "1.0.0",
  "scripts": {
    "build": "react-scripts-ts build"
  },
  "dependencies": {
    "react": "^16.4.0",
    "react-dom": "^16.4.0"
  },
  "devDependencies": {
    "@types/node": "^10.3.2",
    "@types/react": "^16.3.17",
    "@types/react-dom": "^16.0.6",
    "babel-loader": "^7.1.4",
    "babel-preset-react": "^6.24.1",
    "react-scripts-ts": "2.15.1",
    "ts-loader": "^4.4.1",
    "tslint-config-airbnb": "^5.9.2",
    "typescript": "^2.9.1"
  }
}

react-scripts-ts本体の他webpackやTypeScriptやReactなどの依存性を突っ込んでいく

tsconfig.json

{
  "compilerOptions": {
    "module": "esnext",
    "target": "es5",
    "lib": ["es5", "es6", "dom"],
    "jsx": "react",
    "rootDir": "src",
    "moduleResolution": "node"
  },
  "files": [
      "src/index.tsx"
  ],
  "exclude": [
    "node_modules",
    "build"
  ]
}

tslint.json

{
  "extends": "tslint-config-airbnb"
}

終わり。あとは

npm run build

をすればいいだけな模様

余談

tsconfig.prod.jsonだとかなんだかで怒られるっていう事案が検証中に起きてたんだけど原因がreact-scripts-tsのバージョンが2.16.1からはそれが無いと怒られる模様。なので今回はそれを前提としてないので2.15.1を利用している

webpackでTypeScriptプロジェクトをビルド ES7でのfunction bind