번들 파일에서 불필요한 로직을 바벨 플러그인으로 쉽게 삭제하는 방법입니다.
누군가에게는 도움이 되길 바랍니다.
try {
...
console.log(`Data: ${data}`);
} catch (e) {
console.error(`Failed: ${e}`);
}
디버깅이나 로깅을 위해 사용한 console 함수 호출이 릴리즈(Production) 빌드에도 포함된다는 걸 잊기 쉽습니다. 우리가 작성한 소스만 생각하면 개발 빌드에서만 호출되도록 분기하면 되지만 사용하고 있는 많은 모듈에서 사용된 것까지 생각하면 머리가 아픈데요.
걱정하지 마세요. babel-plugin-transform-remove-console
플러그인으로 쉽게 일괄 삭제가 가능합니다.
먼저 플러그인을 설치하세요.
$ yarn add --dev babel-plugin-transform-remove-console
플러그인을 적용하기 전에 비교를 하기 위해 번들 파일을 만들어 보죠. Cake 프로젝트의 번들 크기는 4,073KB 정도네요.
$ react-native bundle --platform ios --dev false --entry-file index.js --bundle-output index.ios.bundle --reset-cache
$ ls -al index.ios.bundle
-rw-r--r-- 1 ifsnow ifsnow **4171408** 5 20 09:18 index.ios.bundle
.babe.config.js (.babelrc)
파일에 플러그인을 추가합니다. env/production
옵션을 사용하면 릴리즈 빌드에서만 동작하도록 설정할 수 있어요.
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
**env: {
production: {
plugins: ['transform-remove-console'],
},
},**
};
설정이 변경된 경우 기존 캐시를 삭제하고 다시 빌드하기 위해 —reset-cache
옵션을 주셔야 해요.
$ react-native bundle --platform ios --dev false --entry-file index.js --bundle-output index.ios.bundle --reset-cache
$ ls -al index.ios.bundle
-rw-r--r-- 1 ifsnow ifsnow **4156284** 5 20 09:20 index.ios.bundle
import PropTypes from 'prop-types';
class Greeting extends React.Component {
render() {
return (
<h1>Hello, {this.props.name}</h1>
);
}
}
Greeting.propTypes = {
name: PropTypes.string
};
런타임에 컴포넌트 속성 타입 체크를 하는 PropTypes는 성능 이슈로 개발 모드에서만 동작합니다. Flow 성능이 점점 좋아지면서 React/RN 프로젝트에서 컴포넌트 타입 체크를 위해 더이상 PropTypes을 사용할 이유가 없어졌습니다. RN Core에서 PropTypes 정의를 걷어내려는 작업도 계속 진행되고 있고요.
불필요하게 번들 파일에 포함되는 PropTypes 정의를 삭제하려면 babel-plugin-transform-react-remove-prop-types
플러그인을 사용하면 됩니다.