React を使ってみる

qiita.com

準備

$ mkdir hello-react-yarn
$ cd hello-react-yarn
$ yarn init
$ mkdir src dist
$ touch .babelrc webpack.config.js index.html src/app.jsx
$ yarn add react react-dom
$ yarn add webpack babel-loader babel-core babel-preset-react babel-preset-es2015 --dev

.babelrc

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

webpack.config.js

module.exports = {
  entry: './src/app.jsx',
  output: {
    path: './dist',
    filename: 'bundle.js'
  },
  devtool: 'inline-source-map',
  module: {
    loaders: [
      {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
};

index.html

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Hello React</title>
</head>

<body>
  <div class="content"></div>
  <script src="./dist/bundle.js"></script>
</body>

</html>

src/app.jsx

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

// コンポーネント名の頭文字は大文字にする
var HelloReact = React.createClass({
  render: function () {
    return (
      <div>
        Hello React!!
      </div>
    );
  }
});

ReactDOM.render(
  <HelloReact />,
  document.querySelector(".content")
);

package.json

{
  "name": "hello-react-yarn",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "react": "^15.3.2",
    "react-dom": "^15.3.2"
  },
  "devDependencies": {
    "babel-core": "^6.17.0",
    "babel-loader": "^6.2.5",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-react": "^6.16.0",
    "webpack": "^1.13.2"
  },
  "scripts": {
    "build": "webpack --progress"
  }
}

webpackの実行

$ yarn run build