create-react-appのメモ
背景
最近 create-react-app を使ったアプリ作成を勉強している。
その過程で、どのファイルが最初に呼ばれるのか(エントリーポイントといえばよいのだろうか?)がわからなくなったので調べてみた。
このメモを作成したときに使ったnpxのバージョンは以下の通り。
$ npx -v 6.12.0
前準備
環境を構築する
$ npx create-react-app myapp
$ cd myapp
上記コマンドにより下記構成が作成される。(※内容が多すぎるためnode_modules
は表示していない。)
$ tree -I node_modules . ├── package.json ├── package-lock.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt ├── README.md └── src ├── App.css ├── App.js ├── App.test.js ├── index.css ├── index.js ├── logo.svg ├── reportWebVitals.js └── setupTests.js 2 directories, 17 files
この状態で npm start
を実行するとブラウザが立ち上がりlocalhost上で動作するページが起動する。
npm startの概要
npm start
に関連する内容は package.json
に記載されている。
ここでは関連する部分のみ抜粋する。
{ "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject" } }
※ここからは予想を含む。
上記"scripts"
要素内の記載からキー:"start"に対応する値:react-scripts start
が実行される。
react-scripts
は./node_modules/.bin/react-scripts
に配置された実行ファイルが使われる。
Folder Structure | Create React App に以下記述を見つけた。
For the project to build, these files must exist with exact filenames:
・public/index.html is the page template;
・src/index.js is the JavaScript entry point.
この内容から、public/index.html
とsrc/index.js
が必須ファイルであると予想がたつ。
またreact-scripts
はデフォルトのエントリポイントとしてpublic/index.html
を扱っているのだろうと推測できる。
stackoverflowの記事
上記推測の裏付けを取るため調べたら関連しそうな記事を見つけた
以下に一番評価された回答の概要を示す(訳はかなり雑です、すいません)。
1. package.json内、start要素
package.json
内のstart
要素から探索を始めた。
"start": "react-script start"
2. react-scripts
上記内容からnode_modules/.bin
以下に存在するreact-scripts
に到達した。
以下に関連する箇所を記載する。
switch (script) { case 'build': case 'eject': case 'start': case 'test': { const result = spawn.sync( 'node', [require.resolve('../scripts/' + script)].concat(args), { stdio: 'inherit' } );
上記内容から../scripts/
ディレクトリ以下のスクリプトを探した。
3. start.js
続いてnpm start
に関連すると予想されるファイル、node_modules/react-scripts/scripts/start.js
を開いた。
このファイル内でwebpackの設定ファイルを見つけた。
これらはnode_modules/react-scripts/config/webpack.config.dev.js
に記載されていた。
以下に関連した箇所を抜粋する。
entry: [ // Finally, this is your app's code: paths.appIndexJs, ], plugins: [ // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, }),
よってwebpack configに含まれているpaths.appIndexJs
で参照されるファイルがエントリファイル(エントリポイント?)
である。
4. paths.js
関連する最後のファイルはpaths.js(おそらくnode_modules/react-scripts/config/paths.js)
である。
const appDirectory = fs.realpathSync(process.cwd()); const resolveApp = relativePath => path.resolve(appDirectory, relativePath); module.exports = { ... appHtml: resolveApp('public/index.html'), appIndexJs: resolveApp('src/index.js'), ... }
5. appHtmlおよびappIndexJs
以上からアプリケーションディレクトリ内のappHtmlはファイルpublic/index.html
であり、appIndexJsはファイルsrc/index.js
である。
まとめ
※公式ページの記載を見つけられなかったので、以下内容は調べた結果からの予想です。
npx create-react-app
を使いアプリをつくる場合、public/index.html
とsrc/index.js
は自動的に読み込まれると予想する。
最後に誤りなどあれば指摘ください。