问题描述
大家好,我搜索并了解到 console.logs
会影响性能。所以我在创建 apk 时选择禁用日志。我找到了但对我不起作用。他们都说将此行添加到 .babelrc
文件,但我没有。所以我创建了 .babelrc
并添加了这一行,但控制台日志仍然出现在浏览器中。
线。
我安装了这个包
npm i babel-plugin-transform-remove-console --save-dev
那我应该怎么改
{
"env": {
"production": {
"plugins": ["transform-remove-console"]
}
}
}
项目结构
解决方法
在 App.js 的最开始 粘贴此代码
console.disableYellowBox = true;
if (!__DEV__) {
console.log = () => {};
console.warn = () => {};
console.error = () => {};
}
,
从任何地方删除所有日志的简单解决方案:
if (!__DEV__) {
for (const iterator of Object.keys(global.console)) {
global.console[iterator] = () => null;
}
}
,
应改为将其添加到 babel.config.js
。
默认的 babel.config.js
如下所示:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],};
你可以进一步调整它
module.exports = api => {
const isProd = api.env('production');
const plugins = isProd ? ["transform-remove-console"] : []
return {
presets: ['module:metro-react-native-babel-preset'],plugins,}
}
使用以下命令构建生产版本时,打开 android/app/src/main/assets/index.android.bundle
以查看是否有任何控制台语句。
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/
这只会从您的代码中删除控制台语句,node_modules
中的库中的任何控制台语句仍将存在。