Absolute Imports and Feature Folders

I prefer to consistently use “absolute import” paths that start from the src folder. Among other things, that makes it easier to move files around, as compared to relative import paths.

Normally, I’d enable that by changing some path resolution options in my Webpack config, but since Create-React-App keeps all the configuration hidden, that’s not an option unless we eject the project. I did some digging around, and it turns out that, at least for now, there’s a semi-undocumented way to enable this in a CRA app without having to eject. If the NODE_PATH environment variable is set, CRA/Webpack will use that in the resolution process. Also, if a .env file exists in the project root, those environment variables will be loaded up. So, we can enable absolute imports by putting those two together. However, the default .gitignore file generated by CRA ignores .env, so we’ll need to fix that:

Commit 53ee842: Enable absolute import paths (such as “features/a/SomeComponent”)

.env

NODE_PATH=src

With that, we can extract the dummy tab panel components into separate feature folders, and import them into App.js:

Commit 4ee6ecb: Extract tab panels into separate feature folders

App.js

import React, { Component } from 'react';
import {
    Header,
    Container,
} from "semantic-ui-react";

-import TabBarContainer from "./features/tabs/TabBarContainer";

import './App.css';

+import TabBarContainer from "features/tabs/TabBarContainer";
+import UnitInfo from "features/unitInfo/UnitInfo";
+import Pilots from "features/pilots/Pilots";
+import Mechs from "features/mechs/Mechs";
+import UnitOrganization from "features/unitOrganization/UnitOrganization";

-const UnitInfo = () => <div>Unit Info content</div>;
-const Pilots = () => <div>Pilots content</div>;
-const Mechs = () => <div>Mechs content</div>;
-const UnitOrganization = () => <div>Unit Organization content</div>;

And, since we’re doing a bit of cleanup, we’ll go ahead and change the page title to say “Project Mini-Mek” instead of “React App”:

Commit 23b6051: Change page title

public/index.html

-   <title>React App</title>
+   <title>Project Mini-Mek</title>

Now we can move on to actually start building the first real parts of our UI.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy