初心者SEのつぶやき

初心者SEのつぶやき

create-react-appを使わずにReactの環境構築を行う方法

やりたいこと

Reactアプリに追加でライブラリをインストールしようとしたら
依存関係の沼にハマったので、create-react-appコマンドを使わずに
Reactの環境構築を行いたい。

実現方法

webpackを用いて環境構築を行う。
webpackは複数のJavaScriptファイルを一つのファイルにまとめて出力するツールである。

プロジェクトの初期化

下記コマンドを実行して初期化&package.jsonを生成する。

npm init -y

webpackのインストール

下記3種をインストールを行う。

  • webpack

  • webpack-cli

  • webpack-dev-server

npm install -D webpack webpack-cli webpack-dev-server

webpackの動作確認

lodashを用いて、動作確認を行う

npm install lodash

./src./distに動作確認用のファイルを作成する。

./src/index.jsに下記を記述する。

import _ from 'lodash';

  function sample() {
    const element = document.createElement('div');
    element.innerHTML = _.join(['webpack','動作確認'], ' ');
    return element;
  }

  document.body.appendChild(sample());

./dist/index.htmlは下記を記述する。

 <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8" />
      <title>sample</title>
    </head>
    <body>
      <script src="main.js"></script>
    </body>
  </html>

下記コマンドを実行してlocalhost:8080に接続し、動作確認ページが表示できたら
正しくインストールされている。

npx webpack server --open --static-directory dist --mode=development

webpackの設定

下記コマンドを実行し、対話形式でwebpackの初期設定を行う。

npx webpack-cli init

今回は下記選択を行なった。(プロジェクトによって選択が変わります。)

  • Which of the following JS solutions do you want to use? (Use arrow keys):Typescript
  • Do you want to use webpack-dev-server? (Y/n) :Y

  • Do you want to simplify the creation of HTML files for your bundle? (Y/n) :Y

  • Do you want to add PWA support? (Y/n) :N
  • Which of the following CSS solutions do you want to use? (Use arrow keys):SASS
  • Will you be using CSS styles along with SASS in your project? (Y/n) :Y
  • Will you be using PostCSS in your project? (y/N):N
  • Do you want to extract CSS for every file? (Use arrow keys):Y
  • Do you like to install prettier to format generated configuration? (Y/n) :Y
  • Pick a package manager: (Use arrow keys):npm
  • Overwrite package.json? (ynarxdeiH) :Y

webpack設定ファイルの変更

下記内容にwebpack.config.jsを置き換える

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

const isProduction = process.env.NODE_ENV === 'production';

const stylesHandler = MiniCssExtractPlugin.loader;

module.exports = {
    entry: './src/index.tsx',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
    },
    devServer: {
        open: true,
        host: 'localhost',
        historyApiFallback: true, // Reactのルーティングを扱うために追加
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'index.html',
        }),
        new MiniCssExtractPlugin(),
    ],
    module: {
        rules: [
            {
                test: /\.(ts|tsx)$/i,
                loader: 'ts-loader',
                exclude: /node_modules/,
            },
            {
                test: /\.css$/i,
                use: [stylesHandler, 'css-loader'],
            },
            {
                test: /\.s[ac]ss$/i,
                use: [stylesHandler, 'css-loader', 'sass-loader'],
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset',
            },
        ],
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.jsx', '.js'],
    },
    mode: isProduction ? 'production' : 'development',
};

Reactのインストール

下記コマンドでreactのインストールを行う。

npm install react react-dom

TypeScriptのインストール

下記コマンドでTypescriptをインストールする。

npm install -D typescript

tsconfig.jsonを削除した後、下記コマンドを実行する。

npx tsc --init

下記コマンドで、reactとreact-domの型定義のインストールを行う。

npm install --save @types/react @types/react-dom

tsconfig.jsonに下記設定を加える。

"compilerOptions": {
  "jsx": "react"
}

動作確認

動作確認前準備

./index.htmlを編集する。

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <div id="app"></div>
</body>

</html>

./src/index.tsxを作成する。

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

const container = document.getElementById('app');
const root = createRoot(container!);

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

./src/App.tsxを作成する。

import React from 'react';

function App() {
  return(
    <div>
      Hello React!!
    </div>
  )
}

export default App;

package.jsonに下記コマンドを加える。

"scripts": {
    "start": "webpack-dev-server --mode development"
}

実行

下記コマンドを実行後、localhost:8080にHello Reactの文言が出力されれば成功となる。

npm start

感想

create-react-appで後から色々なライブラリをインストールすると、依存関係でハマっていたが、0から構築することでカスタマイズしやすくなった。
次のステップとして、eslintやPrettierの設定をまとめられたらと考えている。

今回の内容が参考になったら幸いです。