How to make namespaces and external modules live together in typescript old projects

Viewed 132

Hy everyone,

I'm struggling trying to find a way to solve the following problem:

  1. I have a web application composed by some plain js obtained from old typescript projects
  2. The old typescript projects uses namespaces and transpiles to plain javascript.
  3. I need to extend an old library, coming from one of the projects, with a new part that uses import/export in order to consume some external libraries.
  4. I need also to compile the new part (that extend the old one) in a way that I can use in projects written in old style.

I have tried by creating a new project where

  • I have a file "a.ts" where I'm doing all the imports that I need and export a class

     /// <reference path="../MyOldLib.d.ts" />
     import * as AAA from 'ExternalComponentINeed';
     export class XXX extends I.J.K.W{
       constructor() {
         super();
         ...
       }
       ...
     }
    

where I.J.K is the namespace as in the old library and W is a base class that i need to extend

  • I have file "b.ts" that import the "a.ts" as:

     import * as A_ from "./A";
     declare global {
       namespace I.J.K {
         export import A = A_;
       }
     }
    
  • In the end I have the last file c.ts that declares the namespace

     namespace I.J.K {
       // Force `I.J.K` to be created at runtime.
       (() => {})();
     }
    

I'using webpack to build all together with this config file:

    const path = require('path');
    module.exports = {
      entry:  ['./src/c.ts','./src/b.ts'],
      module: {
      rules: [
       {
          test: /\.tsx?$/,
          exclude: [/node_modules/],
          use: 'ts-loader',
       },
      ],
    },
    resolve: {
      extensions: ['.tsx', '.ts', '.js'],
    },
    node: {global: true},
    output: {
      library: 'mylibrary',
      libraryTarget: 'umd',
      filename: 'mylibrary.js',
      libraryExport: 'default',
      auxiliaryComment: 'Test Comment',
      path: path.resolve(__dirname, 'dist'),
    },
   };

Doing this way I can manage to generate a d.ts file that I can use in the old project, everything compile but in the browser does not work and emits the following:

    Uncaught TypeError: Cannot read properties of undefined (reading 'A')

and here is the point where the code breaks:

    class c extends I.J.K.W  --> I is not defined

We know that it isn't a good way to go but we need a patch. We are planning to refactor our libraries but we can't stop developing and also we would like to have a way to refactor the libraries a little at a time

Any help would be greatly appreciated. Thanks

0 Answers
Related