Naoki Otsu

Reactとwebpack2での環境構築

2017-05-15

webpack2 で React 環境を小さく構築する時の備忘録。
webpack-dev-server でローカルサーバーを立ち上げて、React で単なるhogeを出力させるまで 。

全体の  構成図

/
├public
  └index.html 本番のhtmlファイル
└src
  └index.js 開発時のjsファイル
.babelrc
package.json
webpack.config.js

package.json の作成

yarn init -y

dependencies なモジュールをインストール

yarn add react react-dom

devDependencies なモジュールをインストール

yarn add -D babel-core babel-loader babel-preset-es2015 babel-preset-react webpack webpack-dev-server

.babelrc をルートに作成

{
  "presets": ["es2015", "react"]
}

src と public の 2 つのディレクトリを作成

mkdir src public

public の中に、index.html を作成

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="./bundle.js"></script>
  </body>
</html>

webpack.config.js を作成

const path = require('path')

const src_path = path.resolve(__dirname, 'src')
const public_path = path.resolve(__dirname, 'public')

module.exports = {
  entry: `${src_path}/index.js`,

  output: {
    path: public_path,
    filename: 'bundle.js',
  },

  devServer: {
    contentBase: public_path, // webpack-dev-serverのルートディレクトリ
  },

  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{ loader: 'babel-loader' }],
      },
    ],
  },
}

src の中に、index.js を作成

import React from 'react'
import ReactDOM from 'react-dom'

const App = () => <div>hoge</div>

ReactDOM.render(<App />, document.getElementById('app'))

package.json に"scripts"を追記する

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

ここまでで環境構築が完了したので、
開発時は、yarn start するとhttp://localhost:8080/でローカルサーバー(LiveReroad)が立ち上がり、
本番時は、yarn build すると public に bundle.js が書き出される。

※ただyarn buildは本番用の minify など何も入ってないので、本番用の設定は  適宜入れる必要がある。
https://webpack.js.org/guides/production-build/

[追記 2017/5/15]

PropTypes はクラスの static なプロパティで指定するのが流れのようで、
babel だと、babel-plugin-transform-class-propertiesを使う事が多そうなので追記しておく。

yarn add -D babel-plugin-transform-class-properties
{
  ...
  "plugins": ["transform-class-properties"] // 追記
}

PropTypes の設定例

...
import PropTypes from 'prop-types';

class Counter extends Component {
  static propTypes = {
    value: PropTypes.number.isRequired,
    onIncrement: PropTypes.func.isRequired,
    onDecrement: PropTypes.func.isRequired
  }
  ...
}