Help us understand the problem. What is going on with this article?

Reactで作るSPA入門

More than 3 years have passed since last update.

概要

開発環境の構築

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!と表示されるはず

Miracle-T-Shirt09
ベンチプレス:80kg、デッドリフト:130kg、スクワット:190kg。MDD(Muscle-Driven Development)エバンジェリスト。 https://twitter.com/MiracleTShirt09
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away