Angular2 load script conditionally using Angular CLI?

Can I load scripts conditionally using the Angular CLI ???

In this file, I want to load one script depending on the environment or variable. So in the production process I want to load a script, but not in development. Is there any way to do this? How?

angular-cli.json

... "styles": [ "../node_modules/bootstrap/dist/css/bootstrap.css", "../node_modules/font-awesome/css/font-awesome.min.css", ], "scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/ion-rangeslider/js/ion.rangeSlider.js", "../node_modules/web-animations-js/web-animations.min.js", <---- LOAD HERE ONE SCRIPT DEPENDING ON ENVIRONMENT OR VARIABLE ], "environments": { "source": "environments/environment.ts", "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } ... 
+5
source share
2 answers

While @yuzuri suggested a very complicated solution - you need to edit the node module, which is not a good idea.

Here is an easy way:

You can edit the scripts section in the package.json file to:

 "start": "cp angular-cli-dev.json angular-cli.json && ng serve" "build": "cp angular-cli-prod.json angular-cli.json && ng build" 

Then you should rename your angular-cli.json file to angular-cli-dev.json and angular-cli-prod.json. Each of them should have a different configuration - in my case - different scripts in the "scripts" section.

Hope this helps while we wait for a formal decision

+4
source

.angular-cli.json supports configuration for multiple applications . Therefore, we can set up a completely different configuration with different scripts / styles for the same application.

 "apps": [ { "styles": [ "styles.css" ], "scripts": [ ], "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts", "local": "environments/environment.local.ts" } }, { "styles": [ "styles.css", "../node_modules/select2/dist/css/select2.min.css" ], "scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../node_modules/select2/dist/js/select2.full.min.js" ], "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts", "local": "environments/environment.local.ts" } } 

To serve the default application: $ ng serve --app = 0

or

 $ ng serve --app 0 

To serve an application with a local environment:

 $ ng serve --app=1 --env=local --port=8091 
0
source

Source: https://habr.com/ru/post/1263050/


All Articles