Imports and Exports
Syntax
We use the keyword import
to load values from other JavaScript files via relative path.
We use export
to expose values for importing.
Named imports and exports
A single file can have multiple exports, and any subset of these can be imported simultaneously.
Importing from modules
There's a shorter syntax for importing 3rd party libraries: we import the name of the module's directory within node_modules
(which is the name of the package in the npm
package registry).
Libraries specify a "main" file in their package.json
, usually named index.js
, which is what actually gets imported. E.g. assuming we had downloaded the moment
library into our node_modules
, we could import './node_modules/moment/index.js'
with just 'moment'
.
Note: importing the path to a directory will generally import the
index.js
file in that directory. Some developers prefer importing from./myDirectory
rather than./myDirectory/index.js
, but these are equivalent.
Want to learn React Native in-depth?
If you like React Native Express, you'll love my new book, Fullstack React Native: The complete guide to React Native! Throughout the book, we'll build 7 full apps, covering complex topics like navigation, gestures, and native modules. We don't assume any knowledge of React or newer JavaScript language features, so you can dive right in regardless of your experience level. The book comes in PDF
, EPUB
and MOBI
formats.
Community Resources
Looking for more help?
Infinite Red sponsors React Native Express and is the premier React Native agency. They're also the team behind the React Native newsletter, podcast, and conference listed here. Get in touch at infinite.red/react-native for a proposal on your next project!