Bitfiddler
Bitfiddler

Reputation: 4202

How to reference library already defined at app level in Aurelia ViewModel

Sytemjs is defined in index.html so technically you can do System.import from anywhere in your application and it will work. However during the build, my component which dynamically imports a library when it is used, gives an error:

error TS2304: Cannot find name 'System'

Here is the component code:

import { bindable, bindingMode, customElement, noView } from 'aurelia-framework';

@noView()
@customElement('scriptinjector')
export class ScriptInjector {
  @bindable public url;
  @bindable public isLocal;
  @bindable public isAsync;
  @bindable({ defaultBindingMode: bindingMode.oneWay }) protected scripttag;
  private tagId = 'bootTOCscript';

  public attached() {
    if (this.url) {
      if (this.isLocal) {
        System.import(this.url);
        return;
      }

      this.scripttag = document.createElement('script');
      if (this.isAsync) {
        this.scripttag.async = true;
      }

      this.scripttag.setAttribute('src', this.url);
      document.body.appendChild(this.scripttag);
    }
  }

  public detached() {
    if (this.scripttag) {
      this.scripttag.remove();
    }
  }
}

The project builds and runs just fine despite the error and I tried resolving this by adding:

import System from 'systemjs';

To the component which does resolve the error but at runtime, this import causes Systemjs to look for itself in the app-build bundle which is incorrect. The System.js code is exported seperately. Is there a way to resolve this and have no error message and have it work at runtime?

Upvotes: 2

Views: 84

Answers (1)

Rytmis
Rytmis

Reputation: 32047

This is actually more of a general TypeScript issue when accessing things that implicitly exist in the global scope. What you can do is to declare the variable without actually importing it, like so:

declare var System: System;

(The actual type of System will depend on what your .d.ts looks like)

Upvotes: 1

Related Questions