Exploring the contrast between root directory and base URL in tsconfig

Could you explain the distinction between rootDir and baseUrl in TypeScript?

Based on the documentation provided by TypeScript:

Base URL

It serves as the base directory for resolving non-relative module names. Refer to the Module Resolution documentation for further details.

On the other hand, rootDir is used to

Specify the root directory of input files, primarily utilized to control the output directory structure with --outDir.

In my tsconfig file, I have included

"baseUrl": "app/javascript/src",

and I haven't made any entries for

rootDir

Is this configuration correct? (It seems to be functioning fine, but I'm uncertain about its correctness)

Update: Using rootDir resulted in errors because of absolute paths being used.

This represents my current tsconfig settings. (the baseUrl works correctly)

{
  "compilerOptions": {
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "es6",
      "dom"
    ],
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "jsx": "react",
    "target": "es5",
    "allowSyntheticDefaultImports": true,
    "baseUrl": "app/javascript/src",
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "skipLibCheck": true,
    "allowJs": true,
    "strict": true,
    "outDir": "app/javascript/.dist",
  },
  "exclude": [
    "node_modules",
    "**/*.js",
    "**/*.jsx"
  ],
  "include": [
    "**/*.ts",
    "**/*.tsx"
  ],
  "compileOnSave": false
}

For webpack, path resolutions are handled like this

resolved_paths: ['app/javascript/src', 'app/javascript']

Answer №1

Is it correct that I included the line "baseUrl": "app/javascript/src"?

No, the correct property to use for specifying the root directory of input files is rootDir. The documentation states that rootDir specifies the root directory of input files.

The reason why you are not receiving an error

The property baseUrl only affects non-relative imports. Since your code primarily uses relative imports such as

import something from './something'
, the use of baseUrl does not have a negative impact in this case.

Answer №2

Key Distinctions

Purpose:

  • rootDir: Defines the root source directory
  • baseUrl: Establishes the base directory for resolving module names.

Effect on Output Structure:

  • rootDir: Impacts the structure of output files post-compilation.
  • baseUrl: Facilitates module imports without affecting output files.

Impact on File Selection for Compilation:

  • rootDir: Does not influence file selection for compilation.

  • baseUrl: Specifically influences non-relative imports (not files).

Summary

Hence, rootDir and baseUrl play distinct roles in TypeScript configuration. While rootDir helps manage source and output file structures, baseUrl aids in simplifying path handling during module imports. Employing these settings correctly can greatly enhance project organization and streamline code development."

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

What to do when calling disabled() on a FormControlName causes all form fields to become invalid?

While working with a reactive form, I have observed that setting a formControlName to disabled() can cause the entire form to become invalid. Is there a way to ensure the form remains valid even after disabling a control? console.log('Before:' ...

utilizing a simple input field with typescript

This situation is really getting on my nerves. I have a hidden input box that looks like this: <input type='hidden' id='iFrameDrivenImageValue' value='n/a'> Now, I am attempting to read its value from .ts file in order ...

Is it possible to use a type assertion on the left hand side of an assignment in TypeScript?

While reading the TypeScript documentation, I came across type assertions but it seems they are limited to expressions only. I am looking to assert the type of a variable on the left side of an assignment statement. My specific scenario involves an Expres ...

Encountering issues during npm installation process

Encountering an issue during my attempt to install TypeScript C:\ESAB_Scripting\H5ScriptSDK\Samples>npm install -g TypeScript npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/TypeScript - Not found ...

Tips for launching Nx serve in debug mode for Angular using VSCode

When running my Angular Nx project in the VSCode debugger, I encounter an issue with using yarn. yarn start successfully executes the nx serve command when run from a terminal. However, the same yarn start command fails when executed through VSCode debug ...

Strategies for updating JSON file content as data evolves

I am facing an issue with loading a json file that populates charts. The file is generated from external data sources and stored in the asset directory. Is there a method to automatically load the updated json file? I have attempted to include the code fo ...

Optimal strategies for managing request and response within an Express application

I've developed a REST API using express (and typescript) with the following structure: app.ts routes controllers models Query: Where is the ideal location to handle and construct requests/responses? Is it in routes or controllers? I am ...

The getMonthlyBalances function is providing inaccurate results when calculating stock balances

One of my functions is called getMonthlyBalances, which takes in two arrays - stocks and trades. It calculates the monthly balance of a user's stock holdings based on their trade history. The stocks array includes objects with stock ID, prices, and da ...

What could be causing my ISO datetime string with timezone to alter the time during POST request?

When using the fetch API to POST a JSON object as a string to a service method, I encountered an issue with timezones being converted. Initially, the object contained ISO 8601 strings with timezones (e.g. "StartDate": "2019-04-16T13:46:04-06:00"), but upon ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

Getting the PlayerId after a user subscribes in OneSignal with Ionic2

Currently working on an app with Ionic2 and facing a challenge with retrieving the player id after a user subscribes in order to store it in my database. Any suggestions on how I can retrieve the unique player id of OneSignal users post-subscription? ...

Struggling with AWS CognitoIdentityServiceProvider issues

Trying to access the adminGetUser function using the AWS CognitoIdentityServiceProvider is giving me some trouble. Although the initialization seems correct, I am encountering the following error message. [Nest] 43 - 03/29/2022, 9:18:43 AM ERROR [Except ...

What is the reason for the variance in the inferred generic type parameter between an extended interface and a type alias representing an intersection of interfaces?

Why is the generic type parameter inferred differently in the following toy experiment, depending on whether the template is instantiated with an extended type or with an intersected type? This experiment has been simplified from a real-world example. inte ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

Angular2 - Showing parameters in modal interface

I am working on an Angular5 app and have a component.html file with a function called markerClick that opens a modal. However, I am facing challenges in displaying the item.lat parameter in the modal and would appreciate your assistance. Below is the code ...

Enhance Express Middleware with Typescript for advanced functionality

Currently in the process of developing a REST API using Express and Typescript, I am encountering difficulties when trying to extend the Request/Response objects of Express. Although my IDE shows no errors, Typescript throws TS2339 Errors during compilati ...

Running "npm start" is causing a "SyntaxError: Unexpected token import" error to appear on a typical Angular 2 project when I try to run it

After attempting npm update, npm start then install, I encountered an error right at the beginning of loading the app. It's puzzling that it doesn't recognize "import", which is the first word in the standard bootstrapping file. The stacktrace ...

Error in VueJS/Typescript: Module 'my-module' or its type declarations are not found

Hey fellow developers! I'm currently working on a Vue2 setup with Nuxt and Typescript. I'm facing an issue while trying to install the awesome vue-slick-carousel module via yarn. When attempting to import the module in my component, Typescript th ...

Angular2 ERROR: Unhandled Promise Rejection: Cannot find a matching route:

I'm facing an issue with my Angular2 application while utilizing the router.navigateByUrl method. Within my component, there is a function named goToRoute, structured as follows: router.goToRoute(route:string, event?:Event):void { if (event) ...

Getting the subclass type dynamically within a method of an inherited class in TypeScript

I am working with a class structure. class Node { children: Node[]; } This class is inherited by various other classes. class Block extends Node { // ... } In each of the inherited classes, I want to include a function named replaceChild: const b ...