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