LoginSignup
8
4

More than 5 years have passed since last update.

ReactでHelloWorld

Last updated at Posted at 2018-01-29

ローカル環境構築

1. ディレクトリ作成する

$ mkdir reactApp
$ cd reactApp

2. npm初期化

$ npm init -y

-yで自動的にyesしてくれる (-f --force と同義)

3. Javascriptのビルド関連パッケージを入れる

$ npm i --save react react-dom
$ npm i -D babel-core babel-loader babel-preset-es2015 babel-preset-react
$ npm i -D webpack webpack-dev-server

面倒なのでまとめておりゃっと
dependenciesとdevdependenciesは分けてみた

4. babel設定

$ touch .babelrc
.babelrc
{
  "presets": ["react", "es2015"]
}

5. webpack設定

$ touch webpack.config.js
webpack.config.js
module.exports = {
  entry: './app.js',
  output: {
    path: __dirname + './dist',
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader'
      }
    ]
  }
}

ブラウザリロードタスクも設定追加

package.json
...
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack",
    "start": "webpack-dev-server --hot --inline"
  }
...

npm run buildでビルド
npm startで自動リロードしてくれる

6. React実装

app.js
import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component{
  render(){
    return(
      <div>Hello World</div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("content"))
index.js
<html lang="jp">
<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>React Document</title>
</head>
<body>
  <div id="content"></div>
  <script src="./dist/bundle.js"></script>
</body>
</html>

<body />以外はテキトーに

7. 実行

$ npm run build
$ npm start

正常にstartしたらブラウザでhttp://localhost:8080で確認できる

8
4
1

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
8
4