LoginSignup
0
1

More than 5 years have passed since last update.

【React】create-react-appを使わずにReactの開発環境を構築する

Last updated at Posted at 2019-03-23

はじめに

ReactでWebアプリケーションを作る際、create-react-appを使って環境を構築することが多いと思う。だがwebpackの設定をカスタマイズしたいケース、create-react-appでインストールされるreact-scriptsが邪魔になるケースなど、独自で環境を構築したいときどうすれば環境を作れるのだろうか。このような疑問を持っている方のために、Reactの環境構築の方法をここに記す。

webpackとbabelの導入

webpackは、複数のファイルをひとつにまとめるツールで、babelはES6等新しい書き方をしたjavascriptをどのブラウザでも読み込めるよう変換するツールです。

※プラグインもインストールしています。

mkdir react-env
cd react-env
npm install -D @babel/core @babel/preset-env @babel/preset-react babel-loader file-loader url-loader webpack webpack-cli webpack-dev-server html-webpack-plugin

webpackとbabelの設定

webpackとbabelを利用する設定を書きます。

webpackの設定

webpack.config.jsを作成しましょう。

webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  devServer: {
    port: 3000,
    contentBase: 'dist'
  },
  resolve: {
    extensions: ['.js', '.jsx']
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use:{
          loader: 'babel-loader'
        },
        include: path.resolve(__dirname, 'src')
      },
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'html/index.html'),

      filename: 'index.html'
    }),
  ]
};

entryには、読み込むファイルを設定します。create-react-appで使ったアプリケーションでいうindex.jsです。outputには読み込んだファイルに紐付くコードをまとめたファイルをどこに出力するか設定します。ここでが、distフォルダにbundle.jsとして出力させるようにしています。

module.exports = {
  ...
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  ...
};

webpack-dev-serverを利用して、ローカル環境でアプリケーションを起動させるとき参照するフォルダと、利用するポート番号を設定します。


module.exports = {
  ...
  devServer: {
    port: 3000,
    contentBase: 'dist'
  },
  ...
}

modulerulesには、ローダーを適用するファイルと、使用するローダーを設定します。ここでは、srcフォルダのjsjsxのファイルをbabel-loaderで、画像ファイルをurl-loaderで変換するように設定しています。

module.exports = {
  ...
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use:{
          loader: 'babel-loader'
        },
        include: path.resolve(__dirname, 'src')
      },
      {
        test: /\.(png|jpg|gif)$/i,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
  ...
}

pluginsではwebpackを拡張できます。今回はhtmlファイルを作成するプラグインを導入しています。htmlフォルダのindex.htmlにwebpackを通じで出力されるbundle.jsを読み込むコードを追記して、outputに出力されます。

module.exports = {
  ...
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'html/index.html'),

      filename: 'index.html'
    }),
  ]
};

babelの設定

webpack.config.jsbael-loaderでも設定できるが、今回は切り出して設定します。

.babelrcを作成しましょう。

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

必要なフォルダとファイルを準備

webpackの設定でわかるように、ビルドさせるエントリーファイルであるsrc/index.js、ビルドされたファイルが出力されるdistフォルダ、distフォルダに作成されるhtmlファイルのもととなるhtml/index.htmlが必要なので作成する。

index.jsは次のセクションで書きます。

├── dist
├── html
│   └── index.html
├── package-lock.json
├── package.json
├── src
│   └── index.js
└── webpack.config.js
index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Test</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Reactアプリケーションを開発

必要なモジュールをインストールします。

npm install --save react react-dom

src/index.jsで「Hello React」を表示させます。

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

ReactDOM.render(
  <h1>Hello React</h1>,
  document.getElementById('root')
)

コマンドの設定

npm startでローカル環境でReactアプリケーションの起動、npm run buildでReactアプリケーションのビルドを行わせます。

package.json
{
  ...
  "scripts": {
    "start": "webpack-dev-server",
    "build": "webpack --mode production --progress"
  },
  ...
}

さいごに

独自でReactの環境を作れるようになれば、Next.jsを使わずにサーバーサイドレンダリングも簡単にできたりもします。ぜひ一度お試しあれ。

0
1
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
0
1