This video is available to students only

JS Module resolution

Before moving on, if you are new to the JavaScript world, you need to know there are some problems with importing JavaScript modules.

Since JavaScript is loosely-typed, you need to import code directly from files. TypeScript does help with imports but it does so with relative paths (for example '../../foo/bar') and if at some point you refactor your code or move it around, then it becomes a pain to change all your imports. We will solve this by using a module resolver (and TypeScript itself).

Another important problem is JavaScript modules get loaded in an unpredictable manner, so if you just trust your imports you might run into issues where some part of your app has not been initialized and you try to invoke it somehow. We will solve this by using a specific folder structure.

Setting up module sensible resolution#

You may have noticed in the previous lesson that all of our import statements are relative.

We will turn all our relative imports into absolute imports. First we need to take care of the JavaScript side, so start by adding the Babel-plugin-module-resolver into your dependencies:

Babel is a tool that transpiles our TypeScript into vanilla JavaScript, and it's already integrated into React Native by default. The plugin module-resolver allows you to add a "root" directory to all your imports. That is, every time you import a module without using a relative syntax (ex. ./), it will assume you are requiring the file from the "root" directory of the project (in our case "./src"), and it will be transpiled accordingly.

Next, on the root of the project, there is a babel.config.js file - open it and modify it so it ends up like this:


This page is a preview of Building React Native Apps for Mac

Start a new discussion. All notification go to the author.