Search code examples
javascripttypescriptangularchromecastsystemjs

How to get systemjs to load module from CDN that is in global format?


The error that I am getting is: EXCEPTION: ReferenceError: cast is not defined in [null]

Writing a custom Chromecast receiver application requires the use of the following js file that exposes the functionality via a global 'cast' variable:

//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js

I want to load this script as a module using systemjs instead of having a script tag in index.html.

This is an Angular2 and TypeScript application so in some service, MyService, I want to be able to import 'cast' and use it.

index.html

    <script>
      System.config({
        packages: {
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        },
        paths: {
          'cast': '//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js'
        },
        meta: {
          '//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js': {format: 'global'}
        },      
});

      System.import('app/main')
            .then(null, console.error.bind(console));
    </script>

myService.ts

import {Injectable} from 'angular2/core';
import cast from 'cast';

@Injectable()
export class MyService {
  public init = () => {
    cast.receiver.logger.setLevelValue(cast.receiver.LoggerLevel.NONE);
  }
  ...
}

A sample Angular2 + TypeScript + Chromecast Receiver application can be cloned from:

https://github.com/rmtuckerphx/angular2-chromecast-receiver-starterkit

This code doesn't currently have any code to load 'cast' using systemjs but could be quickly modified by updating index.html and cast-receiver-manager.service.ts


Solution

  • Try adding

       map: {
         cast-receiver: '//www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver.js'
    }
    

    to your system config then declaring the thing you would like to import from the script in your service via,

    declare var cast;
    

    this will allow your compiler to recognize the name of the thing you are importing.