1

I have to use a third party script library in two version modes, a dev sandboxed one and a prod version.

I was observing angular-cli.json, whose excerpt looks like:

  ...
  **
  "scripts": [ ],
  **
  "environmentSource": "environments/environment.ts",
  "environments": {
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
  }
  ...

Is it possible to load scripts by the environment mode? Like:

...
"script": [
    "dev": "./dev-script.js",
    "prod": "./prod-script.js"
]
...

I am a lit bit new to Angular 4/5 and I reached this post. The problem is that the library loading is conditioned not the "dev" or "prod" mode. I would like something more transparent.

Any clues?

Tristan Hessell
  • 930
  • 10
  • 21
zeh
  • 195
  • 1
  • 2
  • 11

1 Answers1

1

Heres is a possible way (not sure if the best one):

@Injectable()
export class SandboxedService {
    isLoaded: boolean = false;

    constructor() { this.loadScript(); }

    private loadScript() {
        if (!this.isLoaded) {
          new Promise((resolve) => {
            let script: HTMLScriptElement = document.createElement('script');
            script.addEventListener('load', r => resolve());
            script.src = isDevMode() ?
              'https://sanboxed.service/v1/service.js':
              'https://prod.service/v1/service.js';
            document.head.appendChild(script);
            this.isLoaded = true;
          });
        }
    }
}

Thanks for this guy/post

zeh
  • 195
  • 1
  • 2
  • 11