blog

備忘録です。雑多な内容を書きます。

React Nativeで未使用のファイルを探す

それなりに開発が進んでいるReact Nativeのプロジェクトで、バンドルされていない未使用のファイルを探したときのメモ。

まとめ

npx metro get-dependencies --entry-file index.js --platform android --dev false

metro bundlerで依存ファイル一覧を出す。 facebook.github.io

未使用ファイル

運用していると、画像が変わったりして使われなくなるファイルが出てくる。
バンドルされないはずなのでユーザーへの影響はないが、未使用のコードだったりすると邪魔なので消しておきたい。

未使用ファイルの探索

React NativeのJavaScriptバンドラーはMetroを使う。Metroのオプションに依存ファイルを出すオプションがあるため、これを利用して未使用ファイルを探すことができる。

Metro CLI Options | Metro

devオプションなども指定でき、実行すると下記のような出力が得られる。

$ npx metro get-dependencies --entry-file index.js --platform android --dev false --output /tmp/dependencies.txt
$ head /tmp/dependencies.txt
/Users/rk/XXXXX/node_modules/metro-runtime/src/polyfills/require.js
/Users/rk/XXXXX/node_modules/@react-native/polyfills/console.js
/Users/rk/XXXXX/node_modules/@react-native/polyfills/error-guard.js
/Users/rk/XXXXX/node_modules/@react-native/polyfills/Object.es7.js
/Users/rk/XXXXX/index.js
/Users/rk/XXXXX/node_modules/@babel/runtime/helpers/interopRequireDefault.js
/Users/rk/XXXXX/node_modules/expo/build/Expo.js
/Users/rk/XXXXX/node_modules/expo/build/Expo.fx.js
/Users/rk/XXXXX/node_modules/@babel/runtime/helpers/defineProperty.js
/Users/rk/XXXXX/node_modules/expo/build/environment/validate.fx.js

適当にシェルで加工して探す。
プロジェクトルートから実行し、 src/ 以下のファイルを対象にしている。

$ npx metro get-dependencies --entry-file index.js --platform android --dev false --output /tmp/dependencies.txt
$ cat /tmp/dependencies.txt | grep "$(pwd -P)/src"  | sort > /tmp/sorted.txt
$ find "$(pwd -P)"/src -type f | sort > /tmp/files.txt
$ diff -u /tmp/sorted.txt /tmp/files.txt | grep -E "^\+" 

上記を実行して出た結果が未使用ファイルになる。なお、TypeScriptだと型定義ファイルも未使用扱いになっているようだった。