Create React App: import modules using aliases with Webpack and Typescript

Using Webpack and Typescript is possible to forget relative paths and to use aliases for a better developer experience.

Matteo Granzotto
Webtips
Published in
4 min readAug 28, 2020

--

You can find the code of this tutorial here, and follow the guide, step by step, in this PR.
You can take a look at a demo here.

Initialize project using Create React App

Execute the following commands:

Setup the environment and install dependencies

Execute:

To the below question, answer with yes:

You will have the following structure:

Install the dependencies:

Create the architecture folders

Create the following folders inside the src one:

  • assets;
  • components;
  • pages;
  • services.

and inside of all of these folders, create an index.ts file. Inside of every index.ts file, we are going to export the contained subfolders. The syntax that we are going to use will be something like:

Update Webpack configuration to use aliases instead of relative paths

Add to config/webpack.config.js file — in particular in the resolve.alias variables of the return object — the following lines:

in this way we are able to do inside every component:

Update Typescript configuration to use aliases instead of relative paths

The second step, to use aliasing, is to update the Typescript configuration. Add to tsconfig.json file the following lines:

in this way, the Typescript compiler will be able to resolve paths.

Reorganize the files

Now we are going to re-organize the file generated by the npm run eject command.

Starting from the assets folder, we move logo.svg inside a new images folder. And inside the index file, we export the file:

Now, for components, we move the App.css, App.tsx and App.test.ts inside a new folder called App. Inside App/App.tsx file we update the import line import logo from './logo.svg'; in import { Logo as logo } from 'Assets';.

And inside the index file, we export the file:

In the end, we need to update src/index.tsx as the following:

Update config in package.json for running test via Jest

To execute the test with modules as aliases, we need to update the jest configuration in package.json as follow:

Visual Studio Code Tips

Using Visual Studio Code as editor, you can get component names via autocomplete using CTRL+Space (or using your combinations).

Reference

Conclusion

Doing these simple steps you will be able to forget the relative paths and make your folders structure more flexible to the changes.

You can find the code of this tutorial here, and follow the guide, step by step, in this PR.
You can take a look at a demo here.

If you have questions, please write to us an email to info@wavelop.com.

Originally published at https://wavelop.com/en/story/create-react-app-module-import-path-aliasing-with-webpack-typescript/ on August 28, 2020.

Credits

--

--