What are some examples of utilizing paths within the tsconfig.json file?

Exploring the concept of path-mapping within the tsconfig.json file led me to the idea of utilizing it to streamline cumbersome path references:

https://i.sstatic.net/AYmv4.png

The project layout is unconventional due to its placement in a mono-repository that houses various projects and libraries, categorized by company and browser / server / universal.

https://i.sstatic.net/8fC6C.png

I am curious about configuring paths in the tsconfig.json file so that instead of:

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

I could simply write:

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

Do I need to make additional adjustments in the Webpack configuration, or is editing the tsconfig.json file sufficient?

Answer №1

To configure this feature in your tsconfig.json file, you can utilize TypeScript's functionality.

Here is an example of how to do it:

"compilerOptions": {
        "baseUrl": "src", // This must be specified if "paths" is.
         ...
        "paths": {
            "@app/*": ["app/*"],
            "@config/*": ["app/_config/*"],
            "@environment/*": ["environments/*"],
            "@shared/*": ["app/_shared/*"],
            "@helpers/*": ["helpers/*"]
        },
        ...

Keep in mind that the path you specify will be based on your baseUrl and it is essential as per the documentation guidelines.

The use of '@' symbol is optional.

Once you have set it up this way, you can easily make use of it like so:

import { Yo } from '@config/index';

You may observe that the intellisense feature does not currently function in the latest version, therefore it is recommended to adhere to a standard convention for importing/exporting files.

For more information, refer to: Module resolution

Answer №2

To simplify your development workflow, consider using both the baseUrl and paths configuration.

If your project's root directory is located within the main src folder (assuming I understood correctly), update your TypeScript configuration file as follows:

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

To ensure proper module resolution with Webpack, you may also need to include a resolve configuration. For Webpack 2 compatibility, you can add the following lines in your webpack configuration file:

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

Answer №3

Explore these related solutions featuring asterisks

  "baseLocation": ".",
  "routes": {
    "*": [
      "modules/*",
      "source/types/*"
    ]
  },

Answer №4

If you want a simple way to reference your root folder using @, follow this minimalist example:

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"]
    }
  }
}
// Usage example: import * as logUtils from '@/utils/logUtils';

Alternatively, if you prefer to include the src folder in your imports, you can do so with this configuration:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["*"]
    }
  }
}
// Usage example: import * as logUtils from '@/src/utils/logUtils';

Answer №5

I found a solution that works well for me:

npm install --save-dev tsconfig-paths

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

By using this method, all paths in the tsconfig.json file are loaded. Here is an example of a tsconfig.json file:

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

It is important to have both baseUrl and paths configured for this method to work properly.

With this setup, you can then import modules like this:

import {AlarmIcon} from 'assets/icons'

Answer №6

When transitioning from TypeScript to JavaScript, it's important to convert absolute paths back to relative paths for proper functionality. One commonly used tool for this task is tsc.

Although many opt for using tsconfig-paths, I found that it didn't suit my needs due to its runtime path resolution which could impact package size and performance.

To address this, I created my own solution called tscpaths. This tool replaces paths during compilation, eliminating any runtime dependencies or performance issues. Integration is simple by adding a line to your build scripts in the package.json file.

While tscpaths has worked seamlessly for my somewhat complex setup, as with any new project, there may be some challenges with highly intricate configurations. It’s a promising tool that offers efficiency without sacrificing simplicity.

Answer №7

For those utilizing tsconfig-paths without success, consider adjusting the tsconfig.json file:

{
  // ...
  "compilerOptions": {
    "outDir": "dist",
    "rootDir": "src",
    "baseUrl": ".",
    "paths": {
      "@some-folder/*": ["./src/app/some-folder/*", "./dist/app/some-folder/*"],
      // ...
    }
  },
  // ...
}

If @some-folder/some-class is not found by the compiler, it will search in either ./src... or ./dist....

Answer №8

Alejandro's solution was the key for me. However, since I am utilizing the awesome-typescript-loader in conjunction with Webpack 4, I found it necessary to incorporate the tsconfig-paths-webpack-plugin into my webpack.config file to ensure proper resolution of paths.

Answer №9

It’s a matter of perspective. Rather than using the code snippet below

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

We can eliminate the need for the "../../../../../". It seems out of place and is not very clear.

The solution lies in the TypeScript configuration file. Simply set the baseUrl property, and the configuration will handle your relative paths seamlessly.

How to configure: Within the tsconfig.json file, include the following properties.

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

Therefore, ultimately it will appear as follows:

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

This results in a more straightforward, impressive, and easily readable format...

Answer №10

To Utilize:

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

Uncertain if specifying paths is necessary. However, after setting baseUrl to src, I am able to import all directories within the src directory using this method:

import {Home} from "pages";
import {formatDate} from "utils";
import {Navbar} from "components";

Remember to restart your terminal after modifying the tsconfig.json.

Answer №11

For those utilizing TypeScript with Webpack 2 and at-loader, there is an extra step to consider (mleko's solution didn't fully solve the issue 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 } */)
    ]
}

Enhanced path resolution in TypeScript 2.0

Answer №12

If you're looking to simplify your imports in Node.js, one way is to utilize Subpath patterns.

Take for instance, updating your package.json with the following configuration...

{
    "imports": {
        "#lib": "./build/path/to/lib",
        "#lib/*": "./build/path/to/lib/*",
    }
}

This setup allows for cleaner import statements that steer clear of relative paths.

import { something } from "#lib"

Remember, these must begin with a hash and be correctly specified in your package.json linking to your build directory for Node.js to identify them.

In addition, consider including similar configurations in your tsconfig.json file if you're using TypeScript:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "#lib": ["./src/path/to/lib"],
            "#lib/*": ["./src/path/to/lib/*"],
        },
    },
}

Answer №13

It seems like React has recently been updated, and as a result, you are no longer able to define the "paths" in the tsconfig.json file.

React now displays a helpful warning message:

Your tsconfig.json file will undergo the following changes: \

  • compilerOptions.paths must not be set (aliased imports are not supported)

Subsequently, it automatically updates your tsconfig.json by removing the entire "paths" section. To work around this issue, you can execute the command

npm run eject

This action will expand all the configurations of create-react-scripts, incorporating config and scripts directories along with build/configuration files into your project. This also grants more flexibility in controlling how everything is structured, named, etc., through modifications in the {project}/config/* files.

Remember to update your tsconfig.json as follows:

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

Answer №14

Developing a component library

If you're in the process of creating a library that provides UI components (such as react-bootstrap or Ant Design), then these configurations should be beneficial for your project.

"compilerOptions": {
        ....
        "rootDir": "src",
        "baseUrl": ".",
        "paths": {
            "src/*": ["src/*"],
            "components/*": ["src/components/*"],
        }
  },

Answer №15

To better understand how the compiler works, take a look at this resource.

In my project file, I have included baseUrl as shown below:

"baseUrl": "src"

This setup is functioning correctly. Make sure to specify the base directory for your own project.

Answer №16

2021 Solution:

Note: CRA. At first, the concept of incorporating a third-party library or ejecting the app for aliasing seemed unconventional to me. However, after 8 hours of research (and experimenting with ejection), it became evident that this approach is the most efficient.

Step 1.

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

Step 2. Create config-overrides.js file in the root directory of your project and populate it with the following:

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

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

Step 3. Modify 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 are not functioning, include them in the d.ts file. For instance: '@constants': './src/constants', => add in react-app-env.d.ts declare module '@constants';

That's all. You can now proceed using yarn or npm start/build/test commands as usual.

Complete version available in the documentation.

Note: The Using with TypeScript / JavaScript configuration section in the docs did not yield results for me. The error "aliased imports are not supported" persisted during the project build. Hence, I opted for a simpler method. Fortunately, it worked effectively.

Answer №17

/ originates from the base directory. For a relative path, it is necessary to utilize ./ or ../.

Answer №18

It is crucial that the <code>baseUrl
is accurate.

import Product from '@app/components/Product';

src/components/Product.tsx

  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@app/*": [
        "src/*"
      ],
    },

Answer №19

Ensure that you possess the following:

{
    "compileOnSave": true,
    "compilerOptions": {
        "paths": {
            "@styles/*": ["assets/scss/*"]
        }
    },
}

This was causing some trouble for me.

Answer №20

In my experience, Visual Studio Code was having trouble recognizing the path, even though the project was still able to build successfully. The issue turned out to be that I had the paths declaration in a separate tsconfig.app.json file.

After moving the paths property from tsconfig.app.json into the main tsconfig.json, the problem was resolved.


It seems that this is because Visual Studio Code only checks the first tsconfig.json file it encounters in the project's root directory. However, I have not personally verified this. If anyone has more information on this, please feel free to leave a comment.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Typescript object may be null even with its initial value set

1: let a: Record<string, any> | null = {}; 2: a['b'] = 2; Encountered the TS2531: Object is possibly 'null' error on Row 2 despite having an initial value. To address this issue, the code was updated as follows: 1: let a: Record ...

Passing a variable from the second child component to its parent using Angular

Need help with passing variables between two child components Parent Component: deposit.component.html <div> <app-new-or-update-deposit [(isOpenedModal)]="isOpenedModal"></app-new-or-update-deposit> </div> Deposit Component ...

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Utilize a module within a script in the continuous integration setup of a React application

I've created a module to verify if all the necessary environment variables are properly set in a React application. Here's a simple example of how it works: const getEnvironmentVariable = (key: string): string => { if (process.env[key]) { ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...

Tips for creating React/MobX components that can be reused

After seeing tightly coupled examples of integrating React components with MobX stores, I am seeking a more reusable approach. Understanding the "right" way to achieve this would be greatly appreciated. To illustrate my goal and the challenge I'm fac ...

Unleash the potential of a never-ending expansion for grid cells on Canvas

ts: templateStyle = { display: 'grid', 'grid-template-columns': 'calc(25%-10px) calc(25%-10px) calc(25%-10px) calc(25%-10px)', 'grid-template-rows': '150px auto auto', 'grid-gap ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

The parameters provided for ionic2 do not align with any acceptable signature for the call target

Currently, I have 3 pages named adopt, adopt-design, and adopt-invite. To navigate between these pages, I am using navCtrl.push() to move forward and to go back to the previous page. Everything works smoothly on the browser, but when I try to build it for ...

Encountered error while running the `yarn dev` command in NextJS: Assertion `args[0]->IsInt32()' failed

When I execute yarn dev for local development in NextJS, I encounter this error message: /opt/homebrew/Cellar/node/19.9.0/bin/node[8717]: ../src/tcp_wrap.cc:155:static void node::TCPWrap::New(const FunctionCallbackInfo<v8::Value> &): Assertion ` ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

What methods are available to rapidly test Firebase functions?

While working with Typescript on firebase functions, I have encountered challenges in testing and experimenting with the code. Despite using the Lint plugin to identify errors without running the code, I am struggling to run the code and view the output. ...

Ways to update the value within an object in an array stored in a BehaviorSubject?

My initial data is: const menuItems = [{id: 1, active: false}, {id: 2, active: false}] public menuSubject$ = new BehaviorSubject<MenuItem[]>(menuItems); public menu$ = this.menuSubject$.asObservable(); I am attempting to update the element with ...

Retrieve a list of class names associated with a Playwright element

Can anyone suggest the best method to retrieve an array of all class names for an element in Playwright using TypeScript? I've searched for an API but couldn't find one, so I ended up creating the following solution: export const getClassNames = ...

Ensuring TypeORM constraint validations work seamlessly with MySQL and MariaDB

I recently started using TypeORM and I'm trying to incorporate the check decorator in my MySQL/MariaDB database. However, after doing some research on the documentation and online, it seems that the check decorator is not supported for MySQL. I'v ...

No response was forthcoming

I have been trying to send a post request to my login endpoint, but I am not receiving any response. Despite thoroughly checking my code, I am unable to figure out why there is no response being sent back. My backend is built using Express in TypeScript. B ...

The directive for accepting only numbers is not functioning in versions of Chrome 49.xx.xx and earlier

I have implemented a directive in Angular 6 to allow only numbers as input for certain fields. The directive code is shown below: import { Directive, ElementRef, HostListener } from '@angular/core'; @Directive({ selector: '[NumbersOnly]& ...

I am looking for a guideline that permits me to restrict the use of a form validation tool

We have developed our own version of the Validators.required form-validator that comes with Angular 7, but now we need to switch to using CustomValidators.required. To enforce this change, we are considering banning the use of the old Validators.required b ...

JavaScript's Blob to Base64 conversion using FileReader is failing to produce any output

In my typescript application, I am utilizing the FileReader to convert a blob into a base64 image for display within the template. adaptResultToBase64(res: Blob): string { let imageToDisplay : string | ArrayBuffer | null = ''; const re ...