question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to properly make module alias work when building the dist/build folder?

See original GitHub issue

I was experimenting on module alias for typescript and it works during dev, but when I try to build it I always get cannot find module because it is pointing to src file even on build. I tried experimenting on different configs and searched all over but can’t still get it to work. I thought I should just ask here for advice.

Here is my project structure:

|-project
|---src
|-------index.ts  // (where I put require('module-alias/register');)
|-------app (business logic) // where I start using modules e.g import config from '@config/index.config';
|-----------index.ts
|-----------routes
|-------config
|---dist
|---node_modules
|---.env
|---.eslintrc
|---package.json
|---tsconfig.json
|---yarn.lock

Snippet of my package.json

"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
  "dev": "NODE_ENV=development ts-node-dev --respawn --transpileOnly ./src/index.ts",
  "prod": "yarn run build && node -r ./dist/index.js",
  "build": "NODE_ENV=production yarn run build-ts",
  "build-ts": "tsc -p .",
},  
"_moduleAliases": {
  "@config": "./src/config",
  "@util": "./src/util",
  "@middlewares": "./src/app/middlewares",
  "@routes": "./src/app/routes",
  "@controllers": "./src/app/controllers",
  "@models": "./src/app/models",
  "@helpers": "./src/app/helpers"
},

My tsconfig.json

{
  "compilerOptions": {
    "incremental": true,
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true,
    "strict": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "suppressImplicitAnyIndexErrors": true,
    "moduleResolution": "node",
    "baseUrl": "./src",
    "paths": {
      "@config/*": ["config/*"],
      "@util/*": ["util/*"],
      "@middlewares/*": ["app/middlewares/*"],
      "@routes/*": ["app/routes/*"],
      "@controllers/*": ["app/controllers/*"],
      "@models/*": ["app/models/*"],
      "@helpers/*": ["app/helpers/*"]
    },
    "allowSyntheticDefaultImports": true, 
    "esModuleInterop": true 
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

My .eslintrc (not sure if it matters or relevant to this problem)

{
  "extends": ["airbnb-typescript/base"],
  "rules": {
    "import/prefer-default-export": 0
  },
  "settings": {
    "import/resolver": {
      "babel-module": {}
    }
  }
}

Sample of how I use it

import logger from '@util/logger/generic.logger';
import { NextFunction, Request, Response } from 'express';

I hope you can help me point out where I went wrong with my config. Thanks a lot.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

43reactions
PRossetticommented, Feb 11, 2021

@rebirthtobi Thank you very much! This worked perfectly for me! Just two clarifications that could be helpful to someone having this same issue.

  1. I had to remove the _moduleAliases from package.json (otherwise wasn’t working)
  2. I didn’t use the if condition because in the example the same thing is done both in the if and else (like @Kehrlann said)

Just replaced this import 'module-alias/register';

for this

import moduleAlias from 'module-alias';
moduleAlias.addAliases({
  "@shared": `${__dirname}/shared`,
  "@modules": `${__dirname}/modules`,
  "@models": `${__dirname}/models`
});
17reactions
rebirthtobicommented, Aug 15, 2020

For anyone having this issue, this is another way to do this, put it in the entry file at the top before other imports.

import moduleAlias from "module-alias";

if (process.env.NODE_ENV === "production") {
    moduleAlias.addAliases({
        "@shared": `${__dirname}/shared`,
        "@modules": `${__dirname}/modules`,
        "@models": `${__dirname}/models`
    })
} else {
    moduleAlias.addAliases({
        "@shared": `${__dirname}/shared`,
        "@modules": `${__dirname}/modules`,
        "@models": `${__dirname}/models`
    })
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

In TypeScript, what is the proper config to make module alias ...
I tried replacing dist to moduleAliases in package.json . It compiled, however, when I run yarn run dev , it is using the...
Read more >
Module Resolution or Import Alias: The Final Guide - Raul Melo
If you're working in a JS project with some built-in Webpack config and you add Storybook, you'll need to add an alias in...
Read more >
Using module bundlers with Firebase - Google
To run webpack and generate the build folder run the following command. npm run build. Finally, check the dist build ...
Read more >
Setting up Path Alias in TypeScript and tsc build without error
What it does is to look for your source file (.ts) and find the relative path to each module you set as path...
Read more >
How to make an import shortcut/alias in create-react-app?
In order for webpack's aliases to work, you need to configure the default ... React already has built-in import shortcut starting from /src...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found