5
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 1 year has passed since last update.

Webpack?Create React App?No、Vite!! ~ ④Create React AppによるReact開発環境構築 ~

Last updated at Posted at 2023-07-22

前置き

この「Webpack?Create React App?No、Vite!!」シリーズでは、5回に分けて以下の内容を扱います。

  1. JSにおける「コンパイル」「バンドル」「ビルド」の理解
  2. 表題のツールを用いたReact開発環境構築を通じて、1の内容を理解する
  3. viteの技術的な凄みとその「爆速」ぶりを体感

現状以下のようなタイトルを想定しています。

①コンパイル、バンドル、ビルドを理解しよう

②webpackによるReact開発環境構築[バンドラ/コンパイラ編]

③webpackによるReact開発環境構築[開発サーバー/HMR編]←前回

④Create React AppによるReact開発環境構築←今回

⑤ViteによるReact開発環境構築とその技術的な凄み

4.Create React AppによるReact開発環境構築

前回と前々回とで、webpackによる開発環境構築を行ってきました。最低限の開発環境をセットアップするのにも、なかなか多くの設定が必要だったかと思います。今回はCreate React AppというFacebook社(現Meta社)が開発を行っていたツールを扱います。ただ今回開発環境構築やりません。
ツールの解説にとどめたいと思います。というのもCreate React Appがそもそものところ、すでに推奨ツールではなくなっているのです。ということで

警告
今回あくまで「React開発環境構築に使用されてきたビルドツールの変遷を辿る」という趣旨でCreate React Appを扱っていますが、当該ツールはすでにメンテナンスモードに入っており、新機能の開発が行われていません。この記事でも当該ツールの使用を推奨しているわけではありません。以下記事で詳しく書かれているので、ご確認いただけるといいと思います。

4.1.Create React Appとは?

先述したように、Create React AppはMeta社が開発したReactの開発環境を容易にセットアップするためのツールです。これまでやってきたビルドの工程を特に設定をせずとも、よしなにやってくれたりします。

以下はCRAのリポジトリのphilosophy(設計思想)に書かれている内容です。

One Dependency: There is only one build dependency. It uses webpack, Babel, ESLint, and other amazing projects, but provides a cohesive curated experience on top of them.

→後ろでwebpackとか色々使ってるけどあんま意識せず使えるで。俺のことだけ考えてや。

No Configuration Required: You don't need to configure anything. A reasonably good configuration of both development and production builds is handled for you so you can focus on writing code.

→設定ファイルほとんど書かなくていいよ。アプリのコード書くのに集中しようや。

No Lock-In: You can “eject” to a custom setup at any time. Run a single command, and all the configuration and build dependencies will be moved directly into your project, so you can pick up right where you left off.

→"eject"してくれたらいつでも自由にさせたる。あとは自分で好きにやりな。

出来る両親のような振る舞いですね。

4.2.お手軽セットアップ

使い方は本当に簡単でyarn,npmかnpxで初期化なりコマンド叩くなりするだけです。
npxなら

npx create-react-app my-app

npmなら

npm init react-app my-app

yarnなら

yarn create react-app my-app

これするだけでwebpackでやってきたことが設定なしでできちゃう。

4.3.中で何をしてるの?

ejectしてちょっとだけ中を覗きます。

npm run eject

すると何やらでっかいconfigというフォルダが現れました。ちょっとちゃんと見ようとすると大変ですが、webpack.config.jsの中身なんか見ると、これまで進研ゼミを通してやってきたことが基本になっているのがわかると思います。

react-refreshとbabel出てきた!

webpack.config.js
const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
  '@pmmmwh/react-refresh-webpack-plugin'
);
const babelRuntimeEntry = require.resolve('babel-preset-react-app');
const babelRuntimeEntryHelpers = require.resolve(
  '@babel/runtime/helpers/esm/assertThisInitialized',
  { paths: [babelRuntimeEntry] }
);

CSSのローダー読み込んでる!

webpack.config.js
  const getStyleLoaders = (cssOptions, preProcessor) => {
    const loaders = [
      isEnvDevelopment && require.resolve('style-loader'),
      isEnvProduction && {
        loader: MiniCssExtractPlugin.loader,
        // css is located in `static/css`, use '../../' to locate index.html folder
        // in production `paths.publicUrlOrPath` can be a relative path
        options: paths.publicUrlOrPath.startsWith('.')
          ? { publicPath: '../../' }
          : {},
      },
      {
        loader: require.resolve('css-loader'),
        options: cssOptions,
      },

HTMLWebpackPluginだ。

webpack.config.js
    plugins: [
      // Generates an `index.html` file with the <script> injected.
      new HtmlWebpackPlugin(
        Object.assign(
          {},
          {
            inject: true,
            template: paths.appHtml,
          },
          isEnvProduction
            ? {
                minify: {
                  removeComments: true,
                  collapseWhitespace: true,
                  removeRedundantAttributes: true,
                  useShortDoctype: true,
                  removeEmptyAttributes: true,
                  removeStyleLinkTypeAttributes: true,
                  keepClosingSlash: true,
                  minifyJS: true,
                  minifyCSS: true,
                  minifyURLs: true,
                },
              }
            : undefined
        )
      ),

このように内部的にやっていることはwebpackの開発環境構築をやった時に設定したものが基礎になっています。それを上手く隠して、使う側はあんまり気にせず使えるようにしているのですね。こうしたNo Configなビルドツールは、最低限のセットアップだけできれば良いというニーズには非常にマッチすると思います。一方で「より柔軟にカスタマイズして使いたい」といった場合には設定を"eject"して独り立ちしていく必要があります。

少し早いですが、今回はここで終わりです。
次回はいよいよ「爆速」Viteの秘密に迫っていきたいと思います。

5
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
5
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?