TypeScript: sharing type definitions seamlessly between server and client (with React.js)
This note will not be a fully detailed tutorial, as it would repeat many things already explained in the original version. In this note I will explain briefly how to set up your React app (created with create-react-app
) to share types between client and server.
You can find the repo for this demo app here
- Create your app with
create-react-app
npx create-react-app <PROJECT_NAME> --typescript
- Add the exact same
server
directory insidesrc
than in the Vue.js version. Thetsconfig.json
file won't be the exact same though, add the following content
// src/server/tsconfig.json
{
"include": ["*.ts"],
"compilerOptions": {
"module": "CommonJS",
"outDir": "dist",
"esModuleInterop": true
}
}
-
Having created our React app with CRA, is not that easy to customize the webpack configuration used under the hood (props to Vue.js on that, it is really easy to do so). We will need a third-party dependency to customize webpack's development server configuration. In this note, we will be using
react-app-rewired
. Install it withnpm install --save-dev react-app-rewired
and follow the instructions available on their README file. -
Once installed, create a file named
config-overrides.js
right next to yournode_modules
directory and add the following content inside it
const { configureServer } = require("./src/server/dist");
module.exports = {
webpack: function (config, env) {
return config;
},
jest: function (config) {
return config;
},
devServer: function (configFunction) {
return function (proxy, allowedHost) {
const config = configFunction(proxy, allowedHost);
config.before = configureServer;
return config;
};
},
paths: function (paths, env) {
return paths;
}
};
We are doing the same as in the original note, importing our configureServer
function and passing it to the before
property for webpack's development server configuration
- Install
nodemon
(npm install --save-dev nodemon
) and create a file namednodemon.json
right next to yournode_modules
directory. Add the following content inside it
{
"watch": ["src/server"],
"exec": "tsc -p src/server && npm start",
"ext": "ts"
}
- Add a new npm-script to run
nodemon
"scripts": {
"dev": "nodemon",
...
},
And we are done! You can now share type definitions between your node.js backend and your React app seamlessly.
Hope you liked it!
📧 lucianoserruya (at) gmail (dot) com