0.1.2 • Published 7 months ago

@xhsfe/metro-plugin-tree-shaking v0.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

@xhsfe/metro-plugin-tree-shaking

@xhsfe/metro-plugin-tree-shaking can provide tree shaking enhancement by generate optimize manifest in second-pass build.

For detail Design, Please read Design Draft DOC

Quick Start

  1. Add Tree shaking metro presets before module:metro-react-native-babel-preset

babel.config.js

module.exports = {
  presets: [
    ['module:@xhs/metro-plugin-tree-shaking', {}], // +
    ["module:metro-react-native-babel-preset", {}],
  ]
}
  1. Use custom serializer on first build by PRE_BUILD and DISABLE_OPTIMIZE environment variables.
/**
 * metro config for jest testing
 */

const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')
import { serializer } from '@xhsfe/babel-plugin-tree-shaking'

/**
 * Metro configuration
 * https://facebook.github.io/metro/docs/configuration
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {
  // ...
  serializer: {
    customSerializer: process.env.PRE_BUILD && !process.env.DISABLE_OPTIMIZE ? serializer : undefined,
  },
  // ...
}

module.exports = mergeConfig(getDefaultConfig(__dirname), config)
  1. Build twice to generate manifest for optimization and jsbundle separately
# METRO_TREE_SHAKING_CACHE_ROOT is recommended to set under os.tmpdir()
# generate manifest for optimization
PRE_BUILD=1 METRO_TREE_SHAKING_CACHE_ROOT=${METRO_TREE_SHAKING_CACHE_ROOT} react-native bundle --platform=android --entry-file=${ENTRY_FILE} --bundle-output=${BUNDLE_OUTPUT}/main.jsbundle --sourcemap-output=${BUNDLE_OUTPUT}/main.jsbundle.map
# generate optimized jsbundle
METRO_TREE_SHAKING_CACHE_ROOT=${METRO_TREE_SHAKING_CACHE_ROOT} react-native bundle --platform=android --entry-file=${ENTRY_FILE} --bundle-output=${BUNDLE_OUTPUT}/main.jsbundle --sourcemap-output=${BUNDLE_OUTPUT}/main.jsbundle.map

Limitation

  • sideEffect and __PURE__ annotation is ignored currently.
  • Build Time will be double without build cache.
  • Cache invalidated will be more frequently, reverseDependencies should be considered.

When tree-shaking is enabled, transform result is not only generated by input file.

For the example shows below, lib.ts's result is also decided by entry.ts's imports

entry.ts

import { add } from 'lib'

lib.ts

const add = () => {}
const sub = () => {}
export { add, sub }

Production validation

@xhsfe/metro-plugin-tree-shaking has been used under production environment since 2024-04, 17+ application bundle enable it before 2024-12 and get 6% ~ 38% size reduction. We enable it by default in the latest tooling.

Credits

Thanks to:

  • The esbuild project created by @evanw, which inspire the tree shaking design.
0.1.2

7 months ago

0.1.1

8 months ago

0.1.0

8 months ago