Removing log from production mode is not working - react native - react-native

React native documentation state that
"You can also use this babel plugin that removes all the console.* calls. You need to install it first with npm i babel-plugin-transform-remove-console --save-dev, and then edit the .babelrc file under your project directory like this"
{
"env": {
"production": {
"plugins": ["transform-remove-console"]
}
}
}
I didn't find .babelrc file. Hence I made the following changes in babel.config.js file.
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
env: {
production: {
plugins: ["transform-remove-console"]
}
}
};
But it's not working for me. The logs are displayed when I've tested them in Android Studio. What went wrong here?

The documented approach didn't work for my existing project either, but it worked in a new test project. I tried numerous dependency upgrades, adding/removing deps, plugins, etc. trying to figure out the source of the problem, but no luck. So finally I went with this workaround:
module.exports = {
plugins: ['#babel/plugin-proposal-numeric-separator', 'lodash'].concat(
process.env.NODE_ENV === 'production' ? ['transform-remove-console'] : []
),
presets: [
'module:metro-react-native-babel-preset',
['#babel/env', { targets: { node: 6 } }]
]
};

This should work (recommended method)
const presets = ['module:metro-react-native-babel-preset'];
const plugins = ['module:react-native-dotenv'];
if (process.env.ENV === 'prod') {
plugins.push('transform-remove-console');
}
module.exports = {presets, plugins};
Or if you don't want to use any package for this you can do this.
Place this in index.js
if(!__DEV__){
console.log = () => {}
}

Related

Serving a modified asset-manifest.json in CRA using CRACO doesn't work

I have just created a new CRA app. In our organization we have a micro frontend framework which has certain requirements when it comes to the the asset file of each micro frontend app. CRA will by default, create a asset-manifest.json file.
https://github.com/facebook/create-react-app/blob/main/packages/react-scripts/config/webpack.config.js#L656
Now I need to change this file to assets.json and make some structural changes as well. To achieve this I use CRACO and add the WebpackManifestPlugin.
const ManifestPlugin = require('webpack-manifest-plugin');
module.exports = {
webpack: {
plugins: {
// tried removing CRA definition for ManifestPlugin.
// It worked, but had no impact on my problem
// remove: ['ManifestPlugin'],
add: [
new ManifestPlugin({
fileName: 'assets.json',
generate: (seed, files, entrypoints) => {
const js = [],
css = [];
files.forEach((file) => {
if (file.path.endsWith('.js') && file.isInitial) {
js.push({ value: file.path, type: 'entry' });
}
if (file.path.endsWith('.css') && file.isInitial) {
css.push({ value: file.path, type: 'entry' });
}
});
return { js, css };
},
})
]
}
}
};
Whenever I build the application, my new assets.json file is generated as expected.
However, I can't get CRA, or webpack-dev-server I assume, to serve this file while I run my CRA app in development mode. It only resolves to the index.html file. I have looked through CRA source code and can't really find any relevant place where asset-manifest.json is mentioned.
So how do I get webpack-dev-server to serve my assets.json file?
You need to add the ManifestPlugin to webpack.plugins.remove array to receive only the configuration from WebpackManifestPlugin:
...
webpack: {
alias: {},
plugins: {
add: [
new WebpackManifestPlugin(webpackManifestConfig)
],
remove: [
"ManifestPlugin"
],
},
configure: (webpackConfig, { env, paths }) => { return webpackConfig; }
},
...

Vue Storybook doesn't compile with Pug components

I am trying to add storybook to my project, which written using pug. Unfortunately, storybook stops to compile if I create story with component on pug. If I change template lang to html (and template itself), all works just fine.
I had this same issue last night when adding storybook to an existing Vue/Pug project.
Storybook supports extending it's webpack config.
First open the file .storybook/main.js in your project directory.
Here you can add a function for webpackFinal to the object, which received the webpack config as an argument, and u can push additional loaders into the rules.
More info here in the storybook docs:
https://storybook.js.org/docs/vue/configure/webpack
Here is my file where i have added pug and sass support:
const path = require('path');
module.exports = {
"stories": [
"../src/**/*.stories.mdx",
"../src/**/*.stories.#(js|jsx|ts|tsx)"
],
"addons": [
"#storybook/addon-links",
"#storybook/addon-essentials"
],
webpackFinal: async (config, { configType }) => {
// `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION'
// You can change the configuration based on that.
// 'PRODUCTION' is used when building the static version of storybook.
// Make whatever fine-grained changes you need
config.module.rules.push({
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: path.resolve(__dirname, '../'),
});
config.module.rules.push(
{
test: /\.pug$/,
use: [
{ loader: 'pug-plain-loader' }
]
}
);
// Return the altered config
return config;
},
}

Storybook with craco - call a different verson of react-scripts

Storybook currently calls react-scripts. However, I've got some parts of the CRA config overriden with craco. It means my application is invoked with craco ..., rather than react-scripts ....
Is there a clean solution to have Storybook call craco instead?
The solution I came up with is this :
.storybook/main.js :
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.js'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-actions',
'#storybook/addon-links',
'#storybook/addon-viewport/register',
'#storybook/addon-knobs/register',
],
webpackFinal(config, { configType }) {
return {
...config,
resolve: {
alias: {
...config.resolve.alias,
'~': path.resolve(__dirname, '../src/'),
},
},
};
},
};
I was only using the alias feature in my craco file, so here I override webpack config from storybook and only add the alias parameter. For your case, you'll need to add your own config.
The #FR073N solution is good, but since the lasts versions, this throw an error.
One line was missing to fully override correctly the webpack config.
const path = require('path');
module.exports = {
stories: ['../src/**/*.stories.js'],
addons: [
'#storybook/preset-create-react-app',
'#storybook/addon-actions',
'#storybook/addon-links',
'#storybook/addon-viewport/register',
'#storybook/addon-knobs/register',
],
webpackFinal(config, { configType }) {
return {
...config,
resolve: {
...config.resolve, // <= HERE
alias: {
...config.resolve.alias,
'~': path.resolve(__dirname, '../src/'),
},
},
};
},
};
I've successfully used storybook-preset-craco with #storybook#6.3.5 and react-scripts#4.0.3 and #craco/craco#6.2.0 in a new CRA TypeScript project.

How to debug babel.config.js

I've noticed that there are virtually no info from babel on incorrect configuration. For example I've created new app with react-native-cli, installed decorators plugin and filled my babel.config.js as follows:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: ['#babel/plugin-proposal-decorators', { legacy: true }],
};
And there were the same complain as if no plugin is installed. Correct config would be:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [['#babel/plugin-proposal-decorators', { legacy: true }]],
};
Now I'm trying to install jsx-control-statements and have the same silent fail causing
ReferenceError: Can't find variable: Choose as if no such plugin is installed at all. My babel.config.js is:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
'jsx-control-statements',
['#babel/plugin-proposal-decorators', { legacy: true }],
],
};
So the question is: How do I debug this configuration? How can I get some diagnostic from babel about incorrect configuration/not found packages etc.?
For instance if the presets/plugins are missing or missconfigured, you'll get an error when webpack takes over and try to load all the config. But I think your best shot is to use progressPlugin where you could display each step and see for yourself what is happening.
new webpack.ProgressPlugin((percentage, message, ...args) => {
console.log(percentage, message, ...args);
}),
Another approach, would be using debug module, as nearly all other plugins, modules use it.
DEBUG=* webpack [-c webpack.something.js]
Hope it helps
If you use babel.config.js you could do the following:
module.exports = function(api) {
if (api) {
api.cache(true);
api.debug = process.env.NODE_ENV === 'development' || false;
}
const presets = ['#babel/preset-env'];
const plugins = [
'#babel/plugin-proposal-class-properties',
...
];
return {
presets,
plugins,
};
};

Cannot use Vue component library with npm link

I am building a Vue application and a Vue component library at the same time. So, I would like to setup the library with npm link so I don't have to keep publishing my library package and re-install it in my main application.
My package will be called #company/vue. I can publish it to npm and install/use it in my Vue app like this:
import Vue from 'vue';
import VueComponents from '#company/vue';
Vue.use(VueComponents);
And that works fine. I can access the components in my .vue files and all that.
However, if I follow the standard steps to linking my library:
cd path/to/library
npm link
cd path/to/application
npm link #company/vue
Upon starting dev mode, I get this warning:
export 'default' (imported as 'VueComponents') was not found in '#company/vue'
And of course, nothing in the page loads.
I have to imagine that I'm possibly bundling it wrong?
My build script looks like this:
vue-cli-service build --no-clean --target lib --name company-vue src/index.js
And my index.js that it refers to:
import './index.scss';
import * as components from './components/index.js';
const CompanyVue = {
install(Vue) {
if (this.installed) {
return;
}
this.installed = true;
for (let name in components) {
Vue.use(components[name]);
}
}
};
let GlobalVue = null;
if (typeof window !== 'undefined') {
GlobalVue = window.Vue;
}
else if (typeof global !== 'undefined') {
GlobalVue = global.Vue;
}
if (GlobalVue) {
GlobalVue.use(Plugin);
}
export * from './components';
export default CompanyVue;
This is just the standard way I've seen most libraries do it. And again, it works fine if I pull the package from npm.
This is the stuff related to my bundling in my package.json:
"files": [
"dist",
"src",
"!src/**/*.spec.js",
"!src/**/*.stories.js"
],
"main": "./dist/company-vue.common.min.js",
"module": "./dist/company-vue.umd.min.js",
"browser": "./dist/company-vue.umd.min.js",
"unpkg": "./dist/company-vue.umd.min.js"
And finally, my babel config for the component library:
module.exports = {
presets: ['#babel/preset-env'],
env: {
test: {
presets: [[
'#babel/preset-env',
{
targets: { node: "current" }
}
]]
}
}
}
i found a solution in this issue:
just add this to your vue.config.js in your project:
configureWebpack: {
resolve: {
symlinks:false //npm link
},
}