Client/Server code sharing in Typescript monorepos

Carles Capellas
11 min readJun 27, 2022

Writing a web server on node.js means using the same programming languages on both sides of a web app. Which should allow for sharing a good amount of code between the client and the server apps. Which should be easy when both apps are part of the same monorepo. Then, why do things get complicated when we add Typescript to the mix?

The “replication” problem

In Javascript monorepos, node.js runs the very same files where the source code is written. Therefore, we can we can easily extract the duplicated code to shared files and require them using relative paths 👍 We will need to decide how we ship the shared files to production environments but that’s a separate story.

In Typescript monorepos however, node.js runs a set of transpiled files, which are usually in a different location from the source code files (e.g. a lib or dist folder). This set of transpiled files is generated by turning the Typescript files in the source folder into Javascript files in the distribution folder, replicating the same folder structure. For example:

root
📂 public
📂 src
| 📂 utils
| | 📝 arrays.ts
| 📝 main.ts # import a from './utils/array';
| 📝 express.ts # express.static(path.join(__dirname, '..', 'public'));
📂 dist
| 📂 utils
| | 📝 arrays.js
| 📝 main.js # const a = require('./utils/array'); ✅
| 📝 express.js # express.static(path.join(__dirname, '..', 'public')); ✅
📝 package.json # "npm run start": "node…

--

--

Carles Capellas

Always up for sport, somewhat obsessive about order and, over all things, enthusiastic about coding