Search code examples
javascriptmoduletypescriptcommonjssystemjs

TypeScript and systemjs circle dependency


I have a problem with circle dependencies of modules:

even.ts

import { Odd } from './odd';

export class Even {

    log(){
        return console.log(Odd);        
    }  
}

odd.ts

import { Even } from './even';

export class Odd extends Even{

  log(){
        return console.log(Even);       
    }  

}

Config:

System.config({
  defaultJSExtensions: true,
  baseURL: '/',
  transpiler: 'typescript'
});

System.import('even.js').then( a => console.log(a));

I tried to use requre.js but it can't resolve circle dependencies. In systemjs documentation is written that it can resolve circle depedencies but it doesn't work. The exception is Cannot read property 'prototype' of undefined in __extends function.

Maybe it is better to Use CommonJS, but as I know I cant use module paths from root as I can do it in AMD and SystemJS.


Solution

  • If you just need to fix it then doing

    System.import('./odd') .then(() => System.import('./even')) .then(a => console.log(a));

    will work.

    The issue happens using both TypeScript and Babel and seems to be due to the way that they implement class inheritance in ES5 (via their _extends and _inherits methods in the transpiled code). These methods rely on the module containing the superclass to have been fully executed, however SystemJS does not know this and so it is not executing the modules in the correct order.