Best way to share js object between Typescript interface and NodeJs backend

I am writing an application that uses Angular2 with Typescript as an interface, and NodeJS as a backend. I wrote a javascript object that would like to split between interface and backend. What is the most elegant way to do this?

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

While this works, it raises the browser browser and the exception that appears in the browser console is: "Unprepared ReferenceError: module not defined".

And I would not pollute my console with unnecessary error messages. So is there another, more elegant way to do this?

+2
javascript typescript
Dec 11 '15 at 10:43
source share
1 answer

The β€œcleanest” way that I know is to write a modular script at both ends and create a library of objects that you want to split (so that shared objects are defined in one place)

Customization

Foundation: Typescript with

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

using webpack or browser

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

Library

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

 export default class MyObject{ ... } 

Make sure the library is compiled with declaration: true (for example, in tsconfig): tsc will create js + typing (declarations).

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

Using

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 shared package.json entry.

Backend: just require('shared')

Note. If there are several shared objects, do not use the default export in shared : they cannot be re-exported.

+1
Dec 11 '15 at 13:47
source share



All Articles