Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to share a js object between a Typescript frontend and NodeJs backend

I'm writing an application that uses Angular2 with Typescript as frontend, and NodeJS as backend. I've written a javascript object I wish to share between the frontend and backend. What's the most elegant way to do this?

My initial idea was to write a .d.ts for the frontend, and add a module.exports in the javascript file, so the backend could require('myobject').

While this works, this causes the browser to throw and exception that shows up in the browser console: 'Uncaught ReferenceError: module is not defined'.

And I'd like to not pollute my console with needless error messages. So is there another, more elegant, way of doing this?

like image 531
TheFisherman Avatar asked Dec 11 '15 10:12

TheFisherman


People also ask

Can you combine JS and TS?

The TypeScript compiler supports a mix of JavaScript and TypeScript files if we use the compiler option --allowJs : TypeScript files are compiled. JavaScript files are simply copied over to the output directory (after a few simple type checks).

Can we use node JS for frontend and backend?

Node. js is sometimes misunderstood by developers as a backend framework that is exclusively used to construct servers. This is not the case; Node. js can be used on the frontend as well as the backend.


1 Answers

The "cleanest" way I know to do this is to write modular script on both ends and create a library of objects you want to share (so that the shared objects are defined in a single location)

Set-up

Frontend: Typescript with either

  • target ES6, module: commonjs + Babel (requires Typescript 1.7)
  • or target ES5, module: commonjs

bundled using webpack or browserify

Backend: ES6 (with --harmony flag on node) or ES5

Library

Create a library, say shared, written in Typescript and create the exported Object class

export default class MyObject{ ... }

Make sure the library is compiled with declaration: true (in tsconfig for instance): tsc will generate the js + the typings (declarations).

In the package.json of the shared library, make sure the entry typings is set to point to the generated MyObject.d.ts file. If there are multiple objects; create an index.ts file that re-exports all the objects and point typings to index.d.ts

Usage

Frontend: since you are now using modular JS/TS, import your object directly from Typescript

import MyObject from 'shared'

The typescript transpiler will automatically find the .d.ts definition from the typings entry of shared's package.json.

Backend: simply require('shared')

Note: if there are multiple shared objects, do not use default exports in shared: they cannot be re-exported.

like image 168
Bruno Grieder Avatar answered Nov 01 '22 23:11

Bruno Grieder