[typescript] How to use paths in tsconfig.json?

I was reading about path-mapping in tsconfig.json and I wanted to use it to avoid using the following ugly paths:

enter image description here

The project organization is a bit weird because we have a mono-repository that contains projects and libraries. The projects are grouped by company and by browser / server / universal.

enter image description here

How can I configure the paths in tsconfig.json so instead of:

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

I can use:

import { Something } from "lib/src/[browser/server/universal]/...";

Will something else be required in the webpack config? or is the tsconfig.json enough?

This question is related to typescript node-modules tsconfig

The answer is


Alejandros answer worked for me, but as I'm using the awesome-typescript-loader with webpack 4, I also had to add the tsconfig-paths-webpack-plugin to my webpack.config file for it to resolve correctly


It looks like there has been an update to React that doesn't allow you to set the "paths" in the tsconfig.json anylonger.

Nicely React just outputs a warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

then updates your tsconfig.json and removes the entire "paths" section for you. There is a way to get around this run

npm run eject

This will eject all of the create-react-scripts settings by adding config and scripts directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/* files.

Then update your tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        {…}
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Its kind of relative path Instead of the below code

import { Something } from "../../../../../lib/src/[browser/server/universal]/...";

We can avoid the "../../../../../" its looking odd and not readable too.

So Typescript config file have answer for the same. Just specify the baseUrl, config will take care of your relative path.

way to config: tsconfig.json file add the below properties.

"baseUrl": "src",
    "paths": {
      "@app/*": [ "app/*" ],
      "@env/*": [ "environments/*" ]
    }

So Finally it will look like below

import { Something } from "@app/src/[browser/server/universal]/...";

Its looks simple,awesome and more readable..


You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Solution for 2021.

Note: CRA. Initially the idea of ??using a third party library or ejecting app for alias seemed crazy to me. However, after 8 hours of searching (and trying variant with eject), it turned out that this option is the least painful.

Step 1.

yarn add --dev react-app-rewired react-app-rewire-alias

Step 2. Create config-overrides.js file in your project's root and fill it with :

const {alias} = require('react-app-rewire-alias')

module.exports = function override(config) {
  return alias({
    assets: './src/assets',
    '@components': './src/components',
  })(config)
}

Step 3. Fix your package.json file:

  "scripts": {
-   "start": "react-scripts start",
+   "start": "react-app-rewired start",
-   "build": "react-scripts build",
+   "build": "react-app-rewired build",
-   "test": "react-scripts test",
+   "test": "react-app-rewired test",
    "eject": "react-scripts eject"
}

If @declarations don't work, add them to the d.ts file. For example: '@constants': './src/constants', => add in react-app-env.d.ts declare module '@constants';

That is all. Now you can continue to use yarn or npm start/build/test commands as usual.

Full version in docs.

Note: The 'Using with ts / js config' part in docs did not work for me. The error "aliased imports are not supported" when building the project remained. So I used an easier way. Luckily it works.


Checkout the compiler operation using this

I have added baseUrl in the file for a project like below :

"baseUrl": "src"

It is working fine. So add your base directory for your project.


This works for me:

 yarn add --dev tsconfig-paths

 ts-node -r tsconfig-paths/register <your-index-file>.ts

This loads all paths in tsconfig.json. A sample tsconfig.json:

{
    "compilerOptions": {
        {…}
        "baseUrl": "./src",
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

Make sure you have both baseUrl and paths for this to work

And then you can import like :

import {AlarmIcon} from 'assets/icons'

If you are using paths, you will need to change back absolute paths to relative paths for it to work after compiling typescript into plain javascript using tsc.

Most popular solution for this has been tsconfig-paths so far.

I've tried it, but it did not work for me for my complicated setup. Also, it resolves paths in run-time, meaning overhead in terms of your package size and resolve performance.

So, I wrote a solution myself, tscpaths.

I'd say it's better overall because it replaces paths at compile-time. It means there is no runtime dependency or any performance overhead. It's pretty simple to use. You just need to add a line to your build scripts in package.json.

The project is pretty young, so there could be some issues if your setup is very complicated. It works flawlessly for my setup, though my setup is fairly complex.


/ starts from the root only, to get the relative path we should use ./ or ../


if typescript + webpack 2 + at-loader is being used, there is an additional step (@mleko's solution was only partially working for me):

// tsconfig.json
{
  "compilerOptions": {
    ...
    "rootDir": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}    

// webpack.config.js
const { TsConfigPathsPlugin } = require('awesome-typescript-loader');

resolve: {
    plugins: [
        new TsConfigPathsPlugin(/* { tsconfig, compiler } */)
    ]
}

Advanced path resolution in TypeScript 2.0


Check this similar solutions with asterisk

  "baseUrl": ".",
  "paths": {
    "*": [
      "node_modules/*",
      "src/types/*"
    ]
  },

Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to node-modules

SyntaxError: Cannot use import statement outside a module What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that? Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51 npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json' Cannot find the '@angular/common/http' module How to use paths in tsconfig.json? Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs How to provide a mysql database connection in single file in nodejs Git - Ignore node_modules folder everywhere

Examples related to tsconfig

How to use paths in tsconfig.json?