3
4

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.

Reactの実行開始ファイル「index.tsx」の名前を変更してみる

Last updated at Posted at 2023-03-07

はじめに

create-react-appでテンプレートを作成した場合、エントリーポイントはindex.tsx固定になっています。
ふと、このファイル名を変更するにはどうすればいいか?気になったので実験してみました。

eject('npm run eject')を実行すると、隠されていた設定ファイルとビルドスクリプトが出力されます。

その中にconfig\paths.jsというファイルがあり、各種パスが定義されていました。
appIndexJsを書き換えれば目的が達成できそうです。

ただ、ejectすると後が大変ですのでreact-app-rewired(設定を書き換えるツール)を使って書き換えてみます。

// config after eject: we're in ./config/
module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp(buildPath),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveModule(resolveApp, 'src/index'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  appTsConfig: resolveApp('tsconfig.json'),
  appJsConfig: resolveApp('jsconfig.json'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveModule(resolveApp, 'src/setupTests'),
  proxySetup: resolveApp('src/setupProxy.js'),
  appNodeModules: resolveApp('node_modules'),
  appWebpackCache: resolveApp('node_modules/.cache'),
  appTsBuildInfoFile: resolveApp('node_modules/.cache/tsconfig.tsbuildinfo'),
  swSrc: resolveModule(resolveApp, 'src/service-worker'),
  publicUrlOrPath,
};

前提

create-react-appで作成したプログラム(--template typescript)

手順

① package.jsonのdevDependenciesreact-app-rewiredを追加

  npm i -D react-app-rewired

② ビルドの設定変更を行うためconfig-overrides.jsをルートフォルダに作成

paths.appIndexJsの設定を上書きします。

const path = require('path');
module.exports = {
  paths: function (paths, env) {
    paths.appIndexJs = path.resolve(__dirname, 'src/entry-point.tsx');
    return paths;
  },
};

③ package.jsonを修正

  "scripts": {
-    "start": "react-scripts start",
-    "build": "react-scripts build",
+    "start": "react-app-rewired start",
+    "build": "react-app-rewired build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

index.tsxentry-point.tsxにリネーム

mv index.tsx entry-point.tsx

img10.png

⑤ 動作確認

npm run start

いつもの画面が表示されました

img20.png

参考ページ

react-app-rewiredにはpathだけではなく、webpack, jest, devServerの書き換え方の説明が乗っています。

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?