Using Typescript to resolve a package from a location other than the default node_modules directory

I am currently delving into typescript and eager to start dabbling in creating packages.

Here is the current layout of my project:

myProject/
├── node_modules/
├── src/
│   ├── app
│       ├── index.ts
│   ├── packages
│       ├── database
│           ├── index.ts
├── package.json
├── tsconfig.json

As you can see, my src directory has an app folder for my application implementation and a package folder which is meant to be more abstract, potentially becoming a package in the future.

What I want is to be able to access my package modules by simply writing this in my app folder:

import Database from 'packages/database';

instead of

import Database from '../packages/database/index';

I have tried adjusting the paths configuration in the tsconfig.json file but haven't been successful:

{
  "compilerOptions": {

    ...

    "baseUrl": ".",
    "paths": {
      "packages": ["src/packages"]
    }
  }
}

Of course, I still want to maintain access to the node_modules folder as well...

Is there a way I can make this work?

Thank you for your advice!

Answer №1

One effective strategy to enhance your workflow is by breaking down your tasks into separate packages:

Consider creating a package specifically for handling database operations, which simplifies the database-related tasks.

To implement this approach, you'll need to restructure your project slightly:

myProject/
├── node_modules/
├── src/
│   ├── app
│       ├── index.ts
│   ├── packages
│       ├── database
│           ├── SomeClass.ts
│           ├── index.ts
├── package.json
├── tsconfig.json

Next, ensure to export all components in your database/index.ts file:

import SomeClass from './SomeClass'
import SomeOtherClass from './SomeOtherClass'

export {SomeClass, SomeOtherClass}

You can then access these components from your app folder simply by typing:

import {SomeClass} from 'package-database';

Remember to update your tsconfig.json as well, as it plays a crucial role in this setup:

{
    "compilerOptions": {

    ...

    "baseUrl": ".",
    "paths": {
        "package-database": ["src/packages/database"]
        }
    } 
}

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

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

Do Angular lifecycle hooks get triggered for each individual component within a nested component hierarchy?

I'm exploring the ins and outs of Angular lifecycle hooks with a conceptual question. Consider the following nested component structure: <parent-component> <first-child> <first-grandchild> </first-grandchild& ...

Utilizing generic type and union types effectively in TypeScript

When initializing my class, I often pass in either a value or an object containing information about the value. For instance: new Field<string>('test') new Field<string>({value: 'test', inactive: 'preview'}) Howev ...

Ways to implement the flow of change occurrences in the mat-select component

Seeking assistance with utilizing the optionSelectionChanges observable property within Angular Material's mat-select component. This property provides a combined stream of all child options' change events. I'm looking to retrieve the previ ...

ts-node: The colon symbol was not expected in this context

As I work on developing a backend server for my application, I made the decision to switch from using babel-node as the executor to utilizing ts-node. The command defined in my package.json file is: "server": "cd server && ts-node --project tsconf ...

Creating instance methods in a TypeScript object can be accomplished by defining the methods within the object's class definition. When the object is

As a seasoned Java developer, I've recently been dabbling in TypeScript. Let me introduce you to my user object: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; ...

Having trouble resolving all parameters for the SiteNotificationComponent: (?)

I encountered an issue while attempting to append a component to the DOM. The error message displayed was "Can't resolve all parameters for SiteNotificationComponent: (?).at syntaxError." My goal was to insert HTML content by invoking showNotificatio ...

Implement the usage of plainToClass within the constructor function

I have a dilemma with my constructor that assigns properties to the instance: class BaseModel { constructor (args = {}) { for (let key in args) { this[key] = args[key] } } } class User extends BaseModel { name: str ...

Unable to fake a fetch request using the 'fetch-mock-jest 1.5.1' library

I am attempting to simulate a fetch call using thefetch-mock-jest library, but the code continues to try accessing the remote address and ultimately fails with the error message FetchError: request to https://some.domain.io/app-config.yaml failed, reason: ...

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

Accessing observable property in Angular 2 with TypeScript: A comprehensive guide

My observable is populated in the following manner: this._mySubscription = this._myService.fetchData(id) .subscribe( response => this._myData = response, ...

What are the recommended TypeScript tsconfig configurations for running Node.js 10?

Can someone provide information on the necessary target/libs for enabling Node.js v10.x to utilize async/await without generators? I have found plenty of resources for node 8 but not as much for node 10. ...

Creating Angular UI states with parameters in TypeScript

My Understanding In my experience with TypeScript and angular's ui state, I have utilized "type assertion" through the UI-Router definitely typed library. By injecting $state into my code as shown below: function myCtrl($state: ng.ui.IStateService){ ...

You cannot use Angular 5 to send a post request with a token that has been retrieved

Hello, I'm facing an issue with making a post request in Angular 5. The token I retrieve seems correct as it works fine when tested with Postman. Can someone provide me with a hint or suggestion on what could be going wrong? AuthService.ts getProfi ...

Access data inside nested objects with specified data type

Imagine the code snippet below: type Parent = { children: Child[] } type Child = { label: string } const parent: Parent = { children: [ { label: 'label1' }, { label: 'label2' } ] } How can I use generics to ...

Issue encountered with express-jwt and express-graphql: TypeScript error TS2339 - The 'user' property is not found on the 'Request' type

Implementing express-jwt and graphql together in typescript has been a challenge for me. import * as express from 'express' import * as expressGraphql from 'express-graphql' import * as expressJwt from 'express-jwt' import s ...

Can :[Interface] be considered a correct array declaration in Typescript?

My TypeScript codebase is filled with code snippets like the one below... export interface SomeType { name: string; } export interface SomeComposedType { things: [SomeType]; } Everything was working smoothly until I started experiencing issues su ...