The local types package cannot be built by react-scripts even though tsc has successfully completed the process

I have developed an application with a TypeScript frontend and backend. To streamline the process, I decided to create a shared types module that contains all the necessary types for both components in one centralized location. Rather than going through the hassle of packaging it and using a registry, my aim is to keep it local and leverage npm link.

The basic structure of my project looks like this:

project/
project/backend
project/frontend
project/my-types

All these components are node modules, with the frontend being an un-ejected create-react-app, involving babel and webpack configurations that interact with TypeScript's tsc.

In the package/my-types/package.json file:

{
  "name": "@types/my-types",
  "version": "1.0.0",
  "type": "module",
  "description": "shared types library for all types among all applications",
  "types": "index.d.ts",
  "scripts": {
    "test": "echo \"no tests for this package\"",
    "build": "npx tsc"
  },
  "devDependencies": {
    "@types/ws": "^8.5.3",
    "pg-promise": "^10.12.1",
    "typescript": "^4.8.4"
  }
}

The project/my-types/tsconfig.json configuration:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    ...
  ...
}

The project/backend/tsconfig.json configuration:

{
  "compilerOptions": {
    "types": ["@types/my-types"],
    "allowJs": true,
    ...
  ...
}

The project/frontend/tsconfig.json configuration:

{
  "compilerOptions": {
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    ...
  ...
}

To link the modules, here's what I did:

$ cd project/my-types
$ npm link
$ cd ../backend
$ npm link @types/my-types
$ cd ../frontend
$ npm link @types/my-types

After verification, the folders are structured as follows:

package/frontend/node_modules/@types/my-types
package/backend/node_modules/@types/my-types
my-types/package.json
...

I attempted importing types successfully in the backend:

import {EventPayload} from "my-types/event"
import {Subscriber} from "my-types/db" 

The Main Question

My concerns are:

  1. How can I ensure successful builds in react-scripts for hot-reload and other functionalities?
  2. Is it possible to set outDir: "dist" in my-types/tsconfig.json while maintaining imports like:
import {Thing} from "my-types/scores"
  1. Should the types module be named @types/my-types or is it more practical to name it simply my-types considering it won't be placed in a registry?
...

Answer №1

I've encountered a similar situation where I have a server running on ts-node and a React application that requires access to a shared library. Previously, I would manually copy the common directory into my React /src directory so that the server could utilize it.

  1. I recently found a solution using craco and react-app-alias. With Craco, it even updates my development build automatically when saving changes to the shared TypeScript files.

Below are the configurations I used:

// client/craco.config.js
const { CracoAliasPlugin } = require('react-app-alias-ex');

module.exports = {
    plugins: [
        {
            plugin: CracoAliasPlugin,
            options: {
                alias: { 'common': '../common' },
            },
        },
    ],
}
// client/package.json
  "scripts": {
    "start": "craco start"
  },
  "dependencies": {
    "common": "file:../common",
  1. By following this setup, I can import the uncompiled ts files as if they were packaged. For example:
// client/src/components/Pawn.tsx
import { PawnClass } from 'common/pawn'; // Actually ts file
  1. If you only need to import the ts files like in the previous example, there is no need for special directory structures. I now use the same import type syntax for both client-side and server-side imports.

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

Update the package.json file by adding a new command to an existing script

Is it possible to automatically run npm install before starting the application with npm start? Here is what my package.json file currently looks like: . . "scripts": { "test": "echo \"Error: no test specified\ ...

403 Forbidden: You do not have permission to access this resource

Whenever I attempt to execute a npm install on a project that has Angular as a dependency, I encounter the following error: error 403 Forbidden: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e5eae3f1e8e5f6c4b5aab2aab0"> ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

Difficulty installing yarn for repositories using git+https on Jenkins leads to issues

I'm currently setting up my project on Jenkins to trigger an automatic build for every commit. However, I'm encountering an issue when trying to run yarn install using a NodeJS script in Jenkins. It fails to install the dependencies that are bein ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

I'm attempting to integrate Angular Material into my project but I'm struggling to figure out how to resolve the issue

npm ERR! code ERESOLVE npm ERR! ERESOLVE was unable to find a resolution npm ERR! While resolving: [email protected] npm ERR! Found: [email protected] npm ERR! node_modules/tslint npm ERR! dev tslint@"~6.1.0" from the root projec ...

Angular displays a datalist input as "[object Object]" once a value has been selected

In my form, I have the following section: <div formArrayName="studentPublishing" *ngFor="let all of getstudentPublishing().controls; index as i"> <div class="form-group data"> <input type="text& ...

A guide on compiling Sass without using gulp and Laravel Elixir [SOLUTION]

If you encounter an error similar to this one: https://i.stack.imgur.com/ZqVeV.png You have come to the right place :) ...

What is the reason for the typescript check failing?

When attempting to check for the existence of an attribute using if statement, I encountered an error. Can anyone explain why this happened? I would appreciate any insights on this issue. ...

The styles from bootstrap.css are not displaying in the browser

Currently in the process of setting up my angular 2 project alongside gulp by following this helpful tutorial: I've added bootstrap to the package.json, but unfortunately, it's not reflecting in the browser. I can see it in the node_modules and ...

Discover the initial item in Observable that meets a certain criteria

I am trying to retrieve the first item of type avatar from payload.result within an observable: let result = this.fileService.getAvatarByUserId(2).pipe( map((payload: Payload<FileModel[]>) => payload.result), first((result: FileModel[]) => ...

When launching Cypress, an error occurs indicating that the resource.pak file could not be located

While attempting to implement End to End testing on my application using Cypress, I encountered a setback. Despite installing cypress with "npm install cypress," I faced an error when trying to run the command "npx cypress open" as instructed in their docu ...

Instructions for creating a function that can receive an array of objects containing a particular data type for the value associated with the key K

Seeking guidance on how to define a specific signature for a function that accepts an array of objects and 3 column names as input: function customFunction<T, K extends keyof T>( dataset: T[], propertyOne: K, propertyTwo: K, propertyThird: K ...

Closing a tab in another part of the session using Typescript and Angular

Looking for a solution on how to close a tab within an Angular session that was opened from somewhere else in the same session. For instance: In Component A this.window = this.windowToken.open('Some URL', 'Some Tab Name', 'Some ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Using a git repository as a dependency in your project and then importing the dependency

Struggling to integrate a git repository as a component has been my challenge for the past day. Despite trying multiple approaches, none of them seemed to work when I ran npm i. Here are some of the methods I attempted: npm install from Git in a specific ...

Error: Angular2 RC5 | Router unable to find any matching routes

I am currently encountering an issue with my setup using Angular 2 - RC5 and router 3.0.0 RC1. Despite searching for a solution, I have not been able to find one that resolves the problem. Within my component structure, I have a "BasicContentComponent" whi ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...