7

I am currently working on adding support for Sentry.io in my react-native app. I use react-native-sentry package and there is one requirement: the package should only be imported if certain constant is set to true, for example SHOULD_USE_SENTRY. All sentry configuration is stored in a separate file, which also exposes 2 methods: setupSentry and captureException which are used in the root of the app in the componentDidMount and componentDidCatch respectively. How can I dynamically load those methods in the root component, so that when the value of SHOULD_USE_SENTRY is false I won't get errors thrown after calling my methods? I hope I described my issue clear enough.

1 Answer 1

5

You can't import on condition.

But you can do something similar by creating 2 entry points: folderA/index.js and folderB/index.js

folderA/index.js there you import your module and pass it to your app through props.

import {someModule} from 'someModule';
render(){
    return(<App module={someModule} />);
}

folderB/index.js there you don't import the module, and you pass null instead (or any other value you want)

render(){
    return(<App module={null} />);
}

then in your app component you can now have a condition

App.js

if(this.props.module != null){
    this.props.module.someFunction(); 
}

The only thing left to do is to chose to correct entry point when you start your packager. Use one of the command below depending on your rn version:

react-native start --root folderA

react-native start --projectRoot folderA

By specifying --root or --projectRoot you are telling to the packager to look for the index.js file in the folder you want. You can use this trick if you want different configuration for your project.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.