Jamie
Jamie

Reputation: 2081

How do I import certain parts of a module with require?

I am trying to figure out how I would write the equivalent of:

import { AppRegistry, Image } from 'react-native';

Using require instead of import, such as:

var ReactNative = require('react-native');

How can I achieve the same functionality with require?

Upvotes: 0

Views: 190

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

Use destructuring assignment:

const { AppRegistry, Image } = require('react-native');

Since require returns a module object that contains all the exports of the module (react-native) as properties (try logging require('react-native')), you can select which properties to give explicit bindings to with destructuring assignment, thus it's functionally equivalent to the ES2015 module syntax:

import { AppRegistry, Image } from 'react-native';

Upvotes: 4

Related Questions