Search code examples
node.jstypescriptcommonjs

Writing a Node module in TypeScript for consumption by both TS and JS projects


I have an Express middleware project written in TypeScript. I'd like to consume it in both JS & TS based Node projects.

I'm having trouble configuring my projects to ensure that

  • the upstream project is outputting modules that can be consumed by Node
  • my module can be consumed in JS projects in the format myGreatFunction = require('myGreatFunction') // typeof = function
  • my module can be consumed in the format import myGreatFunction from 'myGreatFunction' // typeof = function
  • my module is not being either output as an object with a .default when that is not expected, or, vice-versa, not being done so when that is indeed expected.

It feels as though I can only achieve some of these aims but not others.

What is the correct incantation of TSConfig properties (upstream & downstream) to ensure this is so?


In the end I settled on a compromise - see below.


Solution

  • In the end I settled on a compromise:

    Library TSConfig:

    {
      "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "declaration": true
      }
    }
    

    Library:

    export = function myGroovyFunction() {...}
    

    Downstream project, TypeScript

    import * as myGroovyFunction from 'mygroovyfunction';
    

    Downstream project, JavaScript

    const myGroovyFunction = require('mygroovyfunction');
    

    The TypeScript import isn't quite as concise as I'd like, but I can deal.