2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webpack4, Babel7 による React開発環境構築

Last updated at Posted at 2019-09-19

ここでは、Webpack4, Babel7 を使用して React の環境構築までを12のステップに分けて説明します。

本記事の編集結果は以下のリポジトリにもあります。
https://github.com/bluemooninc/react-webpack

1.作業フォルダ作成とプロジェクトの初期化

以下、作業フォルダを作成して、npmでプロジェクトの初期化を行います。

mkdir react-webpack
cd react-webpack
## いくつかの質問により package.jsonファイルが生成されます。最初は単にリターンでも構いません。
npm init

2.Reactモジュールのインストール

npm i react react-dom

3.Webpack4モジュールのインストール

ローカルのプロジェクトフォルダにwebpackをインストールします。

$ npm i --save-dev webpack webpack-dev-server webpack-cli

4.Babel7モジュールのインストール

ローカルのプロジェクトフォルダにbabelをインストールします。

$ npm i --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader html-webpack-plugin

ここで、インストールしたモジュールのバージョンを確認してみます。

$ npm list --depth=0
  react-webpack@1.0.0
  ├── @babel/core@7.6.0
  ├── @babel/preset-env@7.6.0
  ├── @babel/preset-react@7.0.0
  ├── babel-loader@8.0.6
  ├── babel-preset-react@6.24.1
  ├── html-webpack-plugin@3.2.0
  ├── react@16.9.0
  ├── react-dom@16.9.0
  ├── webpack@4.40.2
  ├── webpack-cli@3.3.9
  └── webpack-dev-server@3.8.1

5.webpack4の環境設定

Webpack4のin/outのフォルダ設定とモジュールのルール設定、webサーバの設定、プラグインの設定を行います。

touch webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
    mode: 'development',
    entry: [
        './src/index.js'
    ],
    output: {
        path: path.join(__dirname + '/dist'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            test: /\.(js|jsx)$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'babel-loader',
                    options: {
                        presets: [['@babel/preset-env', { modules: false }]]
                    }
                }
            ]
        }]
    },
    resolve: {
        extensions: ['.js', '.jsx'] // use js, jsx file
    },
    devServer: {
        open: true,
        historyApiFallback: true,
        contentBase: path.join(__dirname, '/dist'),
        watchContentBase: true,
        inline: true,
        hot: true,
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Custom template',
            template: 'src/index.html'
        })
    ]
};

6.index.htmlの作成

HtmlWebpackPluginで設定したsrc/index.htmlを作成します。このファイルを編集すれば自動的にwebpackのコンパイルが行われるのですぐにブラウザで確認できます。

mkdir src
touch src/index.html
<!DOCTYPE html>
<html lang="en">
<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>My Document</title>
</head>
<body>
<h1>Start Ok</h1>
<div id="app"></div>
</body>
</html>

7..Babelrcファイルの編集

Reactで動作させる為のプリセットを設定します。

touch .Babelrc
{
  "presets": ["@babel/preset-env", "@babel/preset-react"]
}

8.index.jsの編集

Webpack, Banbelの環境設定ができたので、Reactのルーティングファイルを作成します。

touch src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

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

9.Edit App.js

Reactのアプリケーション部分のサンプルを記述します。

touch src/App.js
import React from 'react';

export default class extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello World!</h1>
            </div>
        );
    }
}

10.package.jsonへスクリプトの追加

サンプルコードができたので、サーバ実行に必要なスクリプトを記述します。 start というコマンドで webpack-dev-serverを起動します。デフォルトポートの8080セキュリティソフトなどで塞がっている事が多いので任意のポートに変更して待ち受けます。

  "scripts": {
    "start": "webpack-dev-server --port 3000",
    "build": "webpack --mode production"
  },

11.ローカルサーバの起動

スクリプトの設定が終わったら、実際にローカルで起動します。HtmlPluginやWebpackを--hot設定にした事で、html,jsファイルを編集すれば webpack がメモリ内で再コンパイルして自動更新してくれます。

npm run start

この時点でのフォルダ構成は以下の通りとなります。

├── .Babelrc
├── node_modules
├── package-lock.json
├── package.json
├── src
│   ├── App.js
│   ├── index.html
│   └── index.js
└── webpack.config.js

12.本番用のビルド

実際にビルドしてファイル出力してみます。buildフォルダに出力されるのでこのファイルをWebサーバに置けば React のWebアプリとして動作します、

npm run build
2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?