Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React Native use require or import?

Tags:

react-native

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?

like image 558
Won Jun Bae Avatar asked May 17 '16 03:05

Won Jun Bae


People also ask

Do I need to import React in React Native?

You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React. createElement .

Should I use import or require?

One of the major differences between require() and import() is that require() can be called from anywhere inside the program whereas import() cannot be called conditionally, it always runs at the beginning of the file. To use the require() statement, a module must be saved with . js extension as opposed to .

Do I need to import require to React?

createElement method. But, React has introduced a new JSX transform with the release of React 17 which automatically transforms JSX without using React. createElement . This allows us to not import React, however, you'll need to import React to use Hooks and other exports that React provides.


3 Answers

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.

like image 124
Keeth Avatar answered Oct 04 '22 05:10

Keeth


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 };.

like image 22
Daniel Schmidt Avatar answered Oct 04 '22 07:10

Daniel Schmidt


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.

like image 33
themefield Avatar answered Oct 04 '22 06:10

themefield