LoginSignup
5
6

More than 3 years have passed since last update.

create-react-appでデコレータを使う

Last updated at Posted at 2019-05-16

TL;DR

create-react-app(以下,CRA)で生成したプロジェクトでESNext構文のデコレータを利用します.CRAではejectすることで内部の設定ファイルを編集することができますが,それはCRAを利用しないのと同義です.一方,CRAでデコレータを利用するためには隠蔽された内部設定を書き換える必要があります.本稿はejectせずにデコレータを有効にする手段を記します.具体的には次の2通りの手段で解決できます.

  1. customize-crareact-app-rewiredを利用して,内部設定を書き換えます.
  2. プロジェクトにTypeScriptを採用します.その場合,tsconfig.json"experimentalDecorators": trueを記載するだけです.

CRAのインストール〜プロジェクト作成

本稿ではyarnを利用します.まずcreate-react-appコマンドを利用できるようにします.
インストール後,CRAでプロジェクトを生成します.TypeScriptプロジェクトの場合は--typescriptオプションをつけて実行します.

yarn global add create-react-app
create-react-app hello-decorators
cd hello-decorators

設定を書き換える(JavaScript)

customize-craとreact-app-rewiredとプラグインのインストール

書き換えに必要なツールとデコレータを有効にするためのBabelプラグインをインストールします.

 yarn add --dev customize-cra react-app-rewired @babel/plugin-proposal-decorators

package.jsonの編集

package.json内の実行コマンドを編集します.react-scriptsreact-app-rewiredに変更します.ejectの行はそのままにしておきます.

package.json
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
},

config-overrides.jsを作成

プロジェクトルート下にconfig-overrides.jsを以下の内容で作成します.
ここで内部設定の修正内容を記載します.

config-overrides.js
const { override, addDecoratorsLegacy } = require('customize-cra')

// Adds legacy decorator support to the Webpack configuration.
module.exports = override(addDecoratorsLegacy())

確認

作業は以上になります.
実際にデコレータが利用可能か確認します.App.jsを編集してデコレータを記載します.
保存後,yarn startで開発サーバを起動してください.

App.js
import React from 'react'
import './App.css'

// Decorator that passes on a 'message' property to a class.
const addMessage = (str) => (component) => {
  component.prototype.message = str
}

@addMessage('Hello world!')
class DecoratorTest extends React.PureComponent {
  render() {
    return <div>{ this.message }</div>
  }
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <DecoratorTest />
      </header>
    </div>
  )
}

export default App
yarn start

Hello world!が表示されれば無事完了です.

tsconfig.jsonを編集する(TypeScript)

プロジェクトにTypeScriptを採用する場合,設定ファイルであるtsconfig.jsonが内部に隠蔽されていないため容易にデコレータを有効にできます.以下の設定を"compilerOptions"内に追加します.

"experimentalDecorators": true

参考

5
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
5
6