Importing and Exporting items
Learn how to import and export items to use them in different files.
We'll cover the following
To write tests for a particular JavaScript file, the items being tested in that file must be accessible from the testing file. This means that the source file must export them, and the test file must import them.
Exporting items
The last line in a JavaScript file often specifies the default export, which is what gets exported if no item is explicitly named. If there is only one thing to export, such as if each component and function is in a separate file, then this last line suffices.
export default App;
In general, classes, functions, and objects can be exported using an export statement, which is usually the last line of the file.
export { getCollatzSequence, Collatz, App };
Typically, the default export is not needed for any given file. However, in the index.js
file of a create-react-app
application, it’s assumed that App
is the default export. For App.js
, we’ll want to keep the default export statement but add the export for the list of items.
Importing items
Once the three items are exported from App.js
, they can then be imported into App.test.js
. If it’s in the same directory as App.js
, the following import
statement will work in ES6 and JSX[33].
import { getCollatzSequence, Collatz, App } from './App';
If the file is in a different directory, use the relative path to get to it, starting with a dot, such as './components/CoolComponent'
. We have to be sure that the relative import remains within the src
directory, or a subdirectory any number of levels below it. The import must give the names of the items to import, but the order in which they are listed is irrelevant.
Get hands-on with 1200+ tech skills courses.