LoginSignup
4
13

More than 5 years have passed since last update.

Reactで作るSPA入門

Last updated at Posted at 2017-04-29

概要

開発環境の構築

cd ~/project
mkdir spa-note
npm init -y
cd spa-note

jsのビルド環境の設定

npm install --save react react-dom # Reactのインストール
npm install --save-dev babel-core babel-loader babel-preset-es2015 babel-preset-react webpack  # babel, webpackのインストール

webpackの設定

webpack.config.jsの作成

webpack.config.js
module.exports = {
  entry: { js: './src/main.js' },
  output: { path: __dirname + '/public', filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
    ],
  },
  devtool: 'source-map',
};

※ 本だとoutput/pathが「’./public’」だったが以下のエラーがでたため、「__dirname + '/public'」に変更したら治った
エラー内容
Bash
Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
- configuration.output.path: The provided value "./public" is not an absolute path!

.babelrcの作成

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

ビルド実行

./node_modules/.bin/webpack

開発用サーバの設定

webpack-dev-serverのインストール

npm install --save-dev webpack-dev-server

webpack.config.jsの修正

webpack.config.js
module.exports = {
  // == 以下を追加 ==
  devServer: {
    contentBase: './public',
    port: 8080,
    inline: true,
    historyApiFallback: true,
  },
  // == 以上を追加 ==
};

htmlの用意

src/index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>SPA Note</title>
    <link ref="stylesheet" href="/bundle.css">
  </head>
  <body>
    <div id="app"></div>
    <script src="/bundle.js"></script>
  </body>
</html>

サーバ起動

 ./node_modules/.bin/webpack-dev-server

動作確認

ブラウザでhttp://localhost:8080/index.htmlにアクセスすれば
Hello SPA!と表示されるはず

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