Won Jun Bae
Won Jun Bae

Reputation: 5389

Does React Native use require or import?

Does React Native use require or import?

All I can find is an old tutorial using require(), but when I run react-native init, I'm getting a project that uses import. Is this due to recent changes in React Native?

What are the main differences?

Upvotes: 31

Views: 40270

Answers (3)

themefield
themefield

Reputation: 4265

React Native now uses Babel for "modules" compilation (doc). If scaffold an app with create-react-native-app, in folder node_modules, there is the Babel plugin named

babel-plugin-transform-es2015-modules-commonjs

, which is referenced across the app.

As name implies, this plugin just transforms ES2015 modules syntax to CommonJS.

For the main differences, I like this answer appearing in another post.

Upvotes: 5

Daniel Schmidt
Daniel Schmidt

Reputation: 11921

The main difference is, that import is ECMAScript 6 syntax and require is ECMAScript 5. Both are interchangeable, but import has a nice syntax for renaming: export { MY_CONST as THE_CONST, myFunc as theFunc };.

Upvotes: 9

Keeth
Keeth

Reputation: 2100

Yes the latest React Native tutorials and examples use the new import syntax.

https://facebook.github.io/react-native/docs/tutorial.html

In terms of the differences between CommonJS (require) and ES6 modules (import), there are some good answers here:

Using Node.js require vs. ES6 import/export

I think most people prefer the new ES6 syntax. However no JS engines implement ES6 modules currently, so it needs to be converted by an ES6 transpiler (e.g. Babel) to require statements. React Native is setup to do this out of the box, so you can just start using import and it should just work.

Upvotes: 26

Related Questions