Skip to main content

Path Aliasing

Path Aliasing#

Once Mongez is installed, it installs link-module-alias which allows us to create aliases for paths that will enhance importing files with readable code.

How to set aliases#

Open package.json file then add _moduleAliases key in the file, so it should look like

package.json
"scripts": {
},"_moduleAliases": {    // list of aliases},

Defining our paths aliases#

Open package.json file in your editor and let's add some aliases

package.json
"scripts": {    // list of scripts},"_moduleAliases": {    "assets": "src/shared/assets",    "shared": "src/shared",    "apps": "src/apps",    "app": "src/apps/front-office"},
apps alias

The apps alias MUST BE always existing as it defines how to load modules lazily.

Generating Aliases#

In package.json file, inside the scripts key, add postinstall key as follows:

package.json
  "scripts": {    "start": "npx react-scripts start",    "build": "npx react-scripts build",    "test": "npx react-scripts test",    "eject": "npx react-scripts eject",    "postinstall": "npx link-module-alias",    "wizard": "npx mongez wizard"  },  "_moduleAliases": {  },

Now le'ts run the command to generate the aliases

yarn postinstall
About postinstall

This command is executed automatically after installing any new package either by yarn or npm.

Take Care of upgrade

When you upgrade any package, make sure to run the postinstall command after upgrading the package yarn postinstall or npm run postinstall.

Directories only, no files#

Please remember to alias only directories, no files shall be aliased as it may sometimes cause to not reading the file.

If you want to make an alias to a file, create a directory with the file name that you want to alias then add index.ts or index.tsx if it contains React Components.

For example, if we want to make an alias to RedButton component in a src/shared/components/RedButton.tsx file

In that case, we'll create a directory named RedButton and has inside it index.tsx, the code inside RedButton.tsx shall be inside RedButton/index.tsx file.

Now let's hide to our packageg.json file and add our new alias

package.json
"scripts": {    // list of scripts},"_moduleAliases": {    "assets": "src/shared/assets",    "shared": "src/shared",    "apps": "src/apps",    "RedButton": "src/shared/components/RedButton",    "app": "src/apps/front-office"},

We can use it now as follows:

import RedButton from 'RedButton';
Do not forget to generate the aliases again

Once you add the module alias, run yarn postinstall or npm run postinstall to generate the new aliases.

Results of module aliasing#

For example, instead of writing the following:

import Button from './../../shared/components/Button';
// Reset of code here 

We can write it as follows:

import Button from 'shared/components/Button';
// Reset of code here