I would like to pass custom arguments to angular-cli
when building an Angular2
(typescript) app. Is this possible? How can I access this arguments in my code?
The scenario is like this: I have one Angular2
app with 2 layouts. Each layout has 3 colors (red, blue, green). I want to build all possible combinations. One app per layout and color => layout1red, layout1green, layout2blue, ...
I want to create 6 JSON config files for each build where I define the layout and color, and maybe some additional properties.
It is possible to create multiple configuration files with
@angular/cli
.As mentioned in docs custom configuration files can be add in the following way:
src/environments/environment.NAME.ts
{ "NAME": 'src/environments/environment.NAME.ts' }
to theapps[0].environments
object in.angular-cli.json
--env=NAME
flag on the build/serve commands.So, you would probably need 6 config files for dev and 6 config files for prod.
And then to access those variables just import environment object from
environment.ts
file.I didn't get your question fully, I can think of two ways of making this happen :
A- Passing arguments when generating a new project :
1- In order to be able to pass arguments to the angular cli, you need understand where would you want it to be used.
If those configurations are used in your layout, you can fork the Angular cli and update it's blueprint and easily add your own configuration.
Here is the components blueprint :
Which looks like this :
you see
selector
? that's the name of the component which you can play with and at the end when you're creating a new project, you can pass your own flags there and use it.But this is not the best idea because you're always in trouble when Angular cli gets updated.
2- The other possible solution is to use
ng eject
This will generate the
webpack
configuration in a seperate file and puts it in your project root folder, you can then play with that file and provide your configuration and make it customised per your app.But again, I'm not sure how do you want to use that configuration.
This is a perfect candidate for your
build time
configuration.3- Use the
environments
configuration:As it's already been answered, this is also very convenient for providing
build time
configuration :Follow
@mikedanylov
's answer and then use it like this in you files :B:
Run time
:This is a better option, you can create a call in your index.html like this :
and then inside the configuration you might have :
and because this is a script, it'l be available everywhere and you can access it in your components :
This will give your more flexibility on updating your configuration in future without having to build your app again.
Obviously you can make the same call through an Ajax call, but I find above to be more application agnostic.