Skip to content

Commit

Permalink
fix(boilerplate): date-fns import syntax (#2510 by @markrickert)
Browse files Browse the repository at this point in the history
Because react-native doesn’t tree-shake, importing things from `date-fns` bundles ALL of the `date-fns` library, which is quite heavy.

Changing from the syntax `import { Locale, format, parseISO } from "date-fns”` to importing them individually like:

```ts
import type Locale from "date-fns/locale"
import format from "date-fns/format"
import parseISO from "date-fns/parseISO"
```

Saves us 0.41 megabytes in the production bundle size of an ignited app. That’s a HUGE savings for such a small syntax thing.

I also added scripts to the boilerplate to use `react-native-bundle-visualizer` through `npx` (which is how i determined this bundle filesize savings).

Before this PR: `yarn bundle:visualize`: 5.13mb
After this PR: `yarn bundle:visualize`: 4.72mb
  • Loading branch information
markrickert authored Oct 3, 2023
1 parent 95b5d54 commit 5eec8c7
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
8 changes: 7 additions & 1 deletion boilerplate/app/utils/formatDate.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { Locale, format, parseISO } from "date-fns"
import I18n from "i18n-js"

// Note the syntax of these imports from the date-fns library.
// If you import with the syntax: import { format } from "date-fns" the ENTIRE library
// will be included in your production bundle (even if you only use one function).
// This is because react-native does not support tree-shaking.
import type Locale from "date-fns/locale"
import format from "date-fns/format"
import parseISO from "date-fns/parseISO"
import ar from "date-fns/locale/ar-SA"
import ko from "date-fns/locale/ko"
import en from "date-fns/locale/en-US"
Expand Down
2 changes: 2 additions & 0 deletions boilerplate/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"postinstall": "node ./bin/postInstall",
"bundle:ios": "react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios",
"bundle:android": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res",
"bundle:visualize": "npx react-native-bundle-visualizer",
"bundle:visualize:dev": "npx react-native-bundle-visualizer --dev",
"release:ios": "echo 'Not implemented yet: release:ios. Use Xcode. More info: https://reactnative.dev/docs/next/publishing-to-app-store'",
"release:android": "cd android && rm -rf app/src/main/res/drawable-* && ./gradlew assembleRelease && cd - && echo 'APK generated in ./android/app/build/outputs/apk/release/app-release.apk'",
"clean": "npx react-native-clean-project",
Expand Down

0 comments on commit 5eec8c7

Please sign in to comment.