- English
- 日本語
概要
みなさんこんにちはcandleです。
今回はcreate-react-appコマンドを使ってreactの開発環境の構築とhello worldあたりまでやってみたいと思います。
過去のreact開発はgulpやwebpackを使って自分でnpmからbabelやその他パッケージをインストールして作成していました。
create-react-appを使えばより簡単にreactの開発環境を構築できます。
本当に、あれほど苦労したのが馬鹿らしくなるくらい簡単なので、やっていきましょう。
前提
nodeがインストールされている
create-react-appコマンドのインストール
create-react-appコマンドはnpmからインストールできます。
これをグローバルで使うので-gフラグ付きでインストールします。
npm install -g create-react-app
reactプロジェクトを作成する
create-react-appでプロジェクトを作ります。
一般に以下の方法で作成します。
今回は helloworldプロジェクトを作ります。
ディレクトリの場所はどこでもかまいません。
私は説明しやすいようにデスクトップに作ります。
create-react-app helloworld
インストールが終わったらプロジェクトに移動します。
cd helloworld ls
サーバの起動
プロジェクトに移動したら、npm startでサーバを起動します。
npm start
こんな感じのメッセージがでて
ブラウザが開いて、以下のようなページが出てきたら成功です。
helloworldプログラムを書く
練習ついでに以下のことをやってみましょう。
- src/components/Input.jsコンポーネントの作成
- src/App.jsの書き換え
src/components/Input.jsコンポーネントの作成
最初にInput.jsコンポーネントを作りましょう。
srcフォルダの中にcomponentsフォルダまだないので作ります。
その後、Input.jsファイルを作成します。
mkdir src/components touch src/components/Input.js
src/components/Input.jsを開いて以下を記述します。
import React from 'react'; const Input = (props) => <input name={props.name} type={props.type} onChange={props.onChange} /> Input.propTypes = { onChange: React.PropTypes.func, name: React.PropTypes.string, type: React.PropTypes.string } Input.defaultProps ={ name: '', type: 'text' } module.exports = Input;
保存しましょう。
src/App.jsの書き換え
reactのメインのプログラムファイルはsrc/App.jsです。
これを好きなエディタで開きます。
emacs src/App.js
このコードに書き換えます。
import React from 'react'; import Input from './components/Input' class App extends React.Component{ constructor(){ super(); this.state = { txt: 'hello world' } } update(e){ this.setState({ txt: e.target.value }) } render(){ return( <div> <p>Text: {this.state.txt}</p> <Input onChange={this.update.bind(this)} /> </div> ) } } export default App;
保存しましょう。
ブラウザで確認する
ブラウザでhttp://localhost:3000にアクセスして見ると以下のような感じになっていて、
テキストフィールドに好きな文字を書き込むと「hello world」のテキストも上書きされます。
まとめ
今まではReact プログラマーが様々な方法で環境構築をしていましたが、1つまとまったような気がします。