You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on May 1, 2020. It is now read-only.
Repository navigation
This repository was archived by the owner on May 1, 2020. It is now read-only.
Introduce a new flag that gets passed in like this:
ionic serve --env qa or ionic run android --env prod
My first thought was that it's value would default to dev for non-prod builds, and prod for prod builds. Developer's can pass in whatever they want, though.
Based on the value that is passed in (or inferred), the config section of the package.json is read. It could look something like this:
If the ionic_env data is not there, we would just move on in the build process. If it is present, we would then perform the text replacement.
Any computed values, sync or async, could be replaced after the build is done. We could either leave this up to the user to add on to the npm script section, or we could provide a hook into the postprocess step. I prefer the latter as it's easier to document and and we can probably make it a 1/2 second faster or so if we do it in app-scripts.
Feedback is appreciated.
Thanks,
Dan
Reacted by Roland Groza, Sh1d0w, David GG, Alexander Shirobokov, Gianfranco P, coldAlphaMan, dnmd, Jono, Ryan Miller, Wade Huang and 43 more
Any computed values, sync or async, could be replaced after the build is done.
Could you expand on this? I didn't quite understand what you mean.
How would the app use these variables, what would the code look like?
One of the comments in another thread mentioned keeping sensitive values out of source control. Could there be a way of reading in a value from a process.env variable to satisfy this requirement?
@danbucholtz this looks great. Angular CLI has a similar implementation.
They have a --target which you can use to tell the CLI to either do a production build (AOT, minification, gzip, etc.) or a dev build. Then there's the --environment flag which we can use to choose the appropriate environment.
I'd disagree with the ionic_env working as proposed though. As you also pointed out, there might be a case when we need to compute some values, and that'd be difficult for some users to figure out. How about the following ionic_env:
Reading a file for instance (that's also possible to do sync). Or perhaps you store some keys in an AWS bucket and you'd like to pull those keys when you compile the app. I could think of plenty of use cases.
One approach I've seen in other places is to allow exporting a function as well as an object inside the configuration file. This could simplify the logic from the app-scripts end and allow you to build the config object dynamically, and only return once you are ready.
If the export is an object, assume it is the config object and use it.
If the export is a function, assume it will return a promise. Call it, wait for it to be resolved and use the resolved value as the config object.
This has the benefit that app-scripts doesn't need to enumerate all the keys in the config object (what about nested keys?) and provides the most flexibility in your config script (what if the fetching of a second async value depends upon another one being resolved first?)
@fiznool true, that'd be much simpler and it would help if a value depends on another one. But the app scripts would still need to enum keys in order to replace, but that's just implementation detail.
Though I'd actually argue that if we export an object, app scripts could potentially run async tasks in parallel so if we'd have more than one property that evaluates to a promise/observable, it could run all of them at once and complete when all are done (something like a Promise.all([ ... ])/Observable.merge(...)).
Yet, the user could do this as well, but if app scripts would do it, it would spare the user of adding extra implementation.
I guess there are many ways this can be tackled, but the simpler the better.
The difficulty there though, is that if one async value depended on
another, you wouldn't be able to resolve the configuration correctly if
app-scripts ran everything in parallel.
Better to put the logic in the hands of the user, IMHO.
I like where @rolandjitsu is going, but instead of tying it down to a specific implementation, is there a way you can take the environment path being used from package.json in the ionic_env object, and then alias it, so it's import { <T> } from @ionic/config or import { <T> } from @ionic/env?
I don't know how the Angular library does aliasing so you can do import { HTTP } from '@angular/http', instead of import { HTTP } from 'angular/modules/wherever/it/lives/http', but that's how I'd implement it.
Give the users the ultimate control of building what they want to export from their environment/config files, but provide a way for those paths to be swapped out during building, and I think properly creating a module alias, which I don't know how to do, is the best approach.
@danbucholtz - I think that is really over-complicated.
Take a look at Webpack's resolve aliasing. This could be done dynamically when starting ionic serve or the other scripts, depending on the env variable:
alias: { Utilities: path.resolve(__dirname, 'src/utilities/'), Templates: path.resolve(__dirname, 'src/templates/') }
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
The only implication to the user is that they'd need to store their config files outside the folder with their source code, as to not include all the files defined. Or maybe not, you can run a glob that excludes the other environment files not being used. Plus, there's no resolution during application running.
For us this isn't necessarily just about env=dev/staging/prod. For some context, we're coming to ionic(v2) from a vanilla cordova app and we use the same codebase to generate multiple different apps primarily distinguished by an 'org_id'. (The app passes this value in server calls to receive different content, amongst a bunch of other differences). We also currently inject the internal and external version numbers since they vary (inconsistently) by org_id.
So, in a nutshell, just passing in "environment" wouldn't solve this problem for us. Why not make this feature align better with unix best practices and simply make all of the current env available inside the application somehow?
for example:
ORG_ID=123 ENVIRONMENT=staging ionic serve
For what it's worth, cordova (or node?) is doing this already automatically. That is, you can access 'process' inside a cordova hook without having to require anything. From that, it's just process.env.ORG_ID == '123'
@danbucholtz I agree, that'd be a reasonable solution. And I'm sure that it would cover most use cases.
@ehorodyski I think it's already possible to use aliasing if you use your own webpack config file (I cannot confirm it, never tried it). But I do see what you mean, though that would not work if you have async operations that need to run in order to compute the env values you want to have available in the app. It would also not work for the use case @josh-m-sharpe describes where you need some env vars that are not exposed by app scripts.
@josh-m-sharpe using the solution proposed would also solve what you're referring to. You'd just need to expose from process.env:
module.exports=function(){// process.env is an object and has all the env varsreturnPromise.resolve(process.env);}
I think it's essential to have a more generic and universal solution, such as the one proposed by @danbucholtz in #762 (comment), that can cover most of the uses cases since the dev needs vary as we can see from the posts on this topic.
Am I the only one that really wants hinting of config keys, e.g. by defining a ConfigInterface? I have not seen it mentioned and I'm not sure how to do it elegantly, though...
@biesbjerg - Right, this is what I'd like accomplished as well. I need to brush up on how to do Typescript module aliasing, so that the paths can be dynamically generated when you run ionic serve.
If ionic-app-scripts doesn't want to implement something like this, I think it would be great to use for yourself. It's really not hard, I've done it before.
@emcniece@gshigeto Do your solutions support using a custom environment file e.g. environment.test.ts when using ngc? If not what modification would be needed?
I'd like to be able to build APKs for the various environments e.g. ionic cordova build android --test.
@GFoley83 Yes, AOT (ngc) compilation works well with this pattern.
The downside of the provided example is that "production" builds end up with double flags, but that's not the end of the world. Here's a sample of my package.json scripts:
The --release and --prod flags are for Ionic. The --env=prod is the custom flag for the provided example Webpack config modification, which matches the ./src/environments/environment.prod.ts file. Using --prod or --release compiles the code with ngc, not sure exactly which one.
Oh, again as a disclaimer, that is totally not "my" solution, it came from William Ghelfi.
On Thu, Feb 22, 2018 at 6:12 PM, Eric McNiece ***@***.***> wrote:
@GFoley83 <https://github.com/gfoley83> Yes, AOT (ngc) compilation works
well with this pattern.
The downside of the provided example is that "production" builds end up
with double flags, but that's not the end of the world. Here's a sample of
my package.json scripts:
"build-aot": "ionic-app-scripts build --release --prod --env=prod",
"production-ios": "ionic cordova build ios --buildConfig ./config/build-ios.json --release --prod --env=prod",
"production-android": "ionic cordova build android --release --prod --env=prod",
"production-browser": "ionic cordova build browser --release --prod --env=prod",
The --prod flag is for Ionic or Cordova, not totally sure which at this
moment. The --env=prod is the custom flag for the provided example
Webpack config modification. Using --prod compiles the code with ngc.
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#762 (comment)>,
or mute the thread
<https://github.com/notifications/unsubscribe-auth/AGP5QYbYkYF0Hrf2AJ4d1yudLIjHITatks5tXSF4gaJpZM4MD5cy>
.
I ended up using a combo of @emcniece and @gshigeto solutions, so massive thanks to them.
I wanted to have environment variables work in Ionic exactly like how they do in Angular CLI (especially given Ionic 4 is somewhere on the horizon), whilst also supporting Karma and Protractor tests.
To use the environment variables, just add import { environment } from '@env/environment';.
Also supports ngc so I can build an Android APK with any environment config e.g. my environment.test.ts config.
This solution also supports using ionic serve with any of your configurations e.g. ionic serve --env=prod
varchalk=require("chalk");vardefaultConfig=require('@ionic/app-scripts/config/webpack.config.js');varionic_env=process.env.IONIC_ENV;varfs=require('fs');varpath=require('path');varenv=require('minimist')(process.argv.slice(2)).env||process.env.IONIC_ENV||'dev';varwebpack=require('webpack');defaultConfig.dev.resolve.alias={"@env/environment": path.resolve(environmentPath('dev'))};defaultConfig.prod.resolve.alias={"@env/environment": path.resolve(environmentPath('prod'))};console.log(chalk.yellow.bgBlack('\nUsing '+env+' environment variables.\n'));if(!!env){varpathToCustomEnvFile=path.resolve(environmentPath(env));defaultConfig[env]=defaultConfig[ionic_env];defaultConfig[env].resolve.alias={"@env/environment": pathToCustomEnvFile};varcustomEnvPlugin=newwebpack.NormalModuleReplacementPlugin(/src\/environments\/environment\.ts/,pathToCustomEnvFile);defaultConfig.prod.plugins.push(customEnvPlugin);defaultConfig.dev.plugins.push(customEnvPlugin);}module.exports=function(){returndefaultConfig;};functionenvironmentPath(env){varfilePath='./src/environments/environment'+(env==='' ? '' : '.'+env)+'.ts';if(fs.existsSync(filePath)){returnfilePath;}console.log(chalk.red.bgWhite('\n'+filePath+' does not exist!\n'));process.exit();}
/test-config/webpack.test.js
varwebpack=require('webpack');varpath=require('path');varfs=require('fs');varchalk=require('chalk');module.exports={devtool: 'inline-source-map',resolve: {alias: {'@env/environment': path.resolve(environmentPath('dev')),},extensions: ['.ts','.js']},module: {rules: [{test: /\.ts$/,loaders: [{loader: 'ts-loader'},'angular2-template-loader']},{test: /\.html$/,loader: 'html-loader?attrs=false'},{test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,loader: 'null-loader'}]},plugins: [newwebpack.ContextReplacementPlugin(// The (\\|\/) piece accounts for path separators in *nix and Windows/(ionic-angular)|(angular(\\|\/)core(\\|\/)@angular)/,root('./src'),// location of your src{}// a map of your routes)]};functionenvironmentPath(env){varfilePath='./src/environments/environment'+(env==='' ? '' : '.'+env)+'.ts';if(fs.existsSync(filePath)){returnfilePath;}console.log(chalk.red('\n'+filePath+' does not exist!\n'));process.exit();}functionroot(localPath){returnpath.resolve(__dirname,localPath);}
@keithdmoore Thanks for your idea to fix this solution. I have followed your solution and able to load files as per what's been set as fileName. But with this solution is it possible to access process.argv.env in TS files anywhere in the application?
I need to access them in my app to load some Mock services for different environments. Earlier(Angular 4 and ionic app scripts 1.x) i was achieving this by setting process.argv.NODE_ENV. I was using Opaque token for the same. Now with Angular 5 and ionic app scripts 3.1.x i am using Injection token and trying to access process.argv.env together with your solution but it always comes as undefined in TS files. Any idea on this?
I had created an issue earlier in Ionic repo, probably should have created here: Here is the link with all info:
I’m sure you could. I followed someone else’s suggestion above. I have a name attribute in my environment model that is the same as what is in the file name. I can access the name in my ts files if I need to.
All, with Ionic 4 release approaching, I know that ENV vars will be handled. If you are using Ionic 3.9.2, here is what I have been using for months to handle ENV vars. It's been pieced together from this and a few other threads.
I ended up using a combo of @emcniece and @gshigeto solutions, so massive thanks to them.
I wanted to have environment variables work in Ionic exactly like how they do in Angular CLI (especially given Ionic 4 is somewhere on the horizon), whilst also supporting Karma and Protractor tests.
To use the environment variables, just add import { environment } from '@env/environment';.
Also supports ngc so I can build an Android APK with any environment config e.g. my environment.test.ts config.
This solution also supports using ionic serve with any of your configurations e.g. ionic serve --env=prod
varchalk=require("chalk");vardefaultConfig=require('@ionic/app-scripts/config/webpack.config.js');varionic_env=process.env.IONIC_ENV;varfs=require('fs');varpath=require('path');varenv=require('minimist')(process.argv.slice(2)).env||process.env.IONIC_ENV||'dev';varwebpack=require('webpack');defaultConfig.dev.resolve.alias={"@env/environment": path.resolve(environmentPath('dev'))};defaultConfig.prod.resolve.alias={"@env/environment": path.resolve(environmentPath('prod'))};console.log(chalk.yellow.bgBlack('\nUsing '+env+' environment variables.\n'));if(!!env){varpathToCustomEnvFile=path.resolve(environmentPath(env));defaultConfig[env]=defaultConfig[ionic_env];defaultConfig[env].resolve.alias={"@env/environment": pathToCustomEnvFile};varcustomEnvPlugin=newwebpack.NormalModuleReplacementPlugin(/src\/environments\/environment\.ts/,pathToCustomEnvFile);defaultConfig.prod.plugins.push(customEnvPlugin);defaultConfig.dev.plugins.push(customEnvPlugin);}module.exports=function(){returndefaultConfig;};functionenvironmentPath(env){varfilePath='./src/environments/environment'+(env==='' ? '' : '.'+env)+'.ts';if(fs.existsSync(filePath)){returnfilePath;}console.log(chalk.red.bgWhite('\n'+filePath+' does not exist!\n'));process.exit();}
/test-config/webpack.test.js
varwebpack=require('webpack');varpath=require('path');varfs=require('fs');varchalk=require('chalk');module.exports={devtool: 'inline-source-map',resolve: {alias: {'@env/environment': path.resolve(environmentPath('dev')),},extensions: ['.ts','.js']},module: {rules: [{test: /\.ts$/,loaders: [{loader: 'ts-loader'},'angular2-template-loader']},{test: /\.html$/,loader: 'html-loader?attrs=false'},{test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,loader: 'null-loader'}]},plugins: [newwebpack.ContextReplacementPlugin(// The (\\|\/) piece accounts for path separators in *nix and Windows/(ionic-angular)|(angular(\\|\/)core(\\|\/)@angular)/,root('./src'),// location of your src{}// a map of your routes)]};functionenvironmentPath(env){varfilePath='./src/environments/environment'+(env==='' ? '' : '.'+env)+'.ts';if(fs.existsSync(filePath)){returnfilePath;}console.log(chalk.red('\n'+filePath+' does not exist!\n'));process.exit();}functionroot(localPath){returnpath.resolve(__dirname,localPath);}
@GFoley83 I've tested your solution but with AOT in specific cases it doesn't work, I ignore the reason.
How to reproduce the error:
log any attribute from your env file on app.module and app.component. The attribute should have different value for each env.
run AOT build with --env=prod ionic build --env=prod --prod
you should observe on your console that app.module log value from dev and app.component log value from prod
It's annoying if you use firebase and need to initiate it with env vars on your app.module (AngularFireModule.initializeApp(ENV.firebase)). At the moment I didn't find a good solution. @writer0713 suggest to rewrite env file using npm hooks, I'll check it.
Activity
fiznool commentedon Feb 17, 2017
Looks interesting! I have a few questions.
Could you expand on this? I didn't quite understand what you mean.
How would the app use these variables, what would the code look like?
One of the comments in another thread mentioned keeping sensitive values out of source control. Could there be a way of reading in a value from a
process.envvariable to satisfy this requirement?rolandjitsu commentedon Feb 17, 2017
@danbucholtz this looks great. Angular CLI has a similar implementation.
They have a
--targetwhich you can use to tell the CLI to either do a production build (AOT, minification, gzip, etc.) or a dev build. Then there's the--environmentflag which we can use to choose the appropriate environment.I'd disagree with the
ionic_envworking as proposed though. As you also pointed out, there might be a case when we need to compute some values, and that'd be difficult for some users to figure out. How about the followingionic_env:And each file would export the following:
Then
@ionic/app-scriptswould require the appropriate env based on the config fromionic_envand for each key it will:Perhaps there could be a better approach, but I thing this would work in most scenarios.
fiznool commentedon Feb 17, 2017
Perhaps I'm missing something, but what sort of use cases would benefit from async computation of values?
rolandjitsu commentedon Feb 17, 2017
Reading a file for instance (that's also possible to do sync). Or perhaps you store some keys in an AWS bucket and you'd like to pull those keys when you compile the app. I could think of plenty of use cases.
fiznool commentedon Feb 17, 2017
Right, I'm with you now. 👍
One approach I've seen in other places is to allow exporting a function as well as an object inside the configuration file. This could simplify the logic from the app-scripts end and allow you to build the config object dynamically, and only return once you are ready.
Something along these lines:
app-scripts would then perform the following
This has the benefit that app-scripts doesn't need to enumerate all the keys in the config object (what about nested keys?) and provides the most flexibility in your config script (what if the fetching of a second async value depends upon another one being resolved first?)
rolandjitsu commentedon Feb 17, 2017
@fiznool true, that'd be much simpler and it would help if a value depends on another one. But the app scripts would still need to enum keys in order to replace, but that's just implementation detail.
rolandjitsu commentedon Feb 17, 2017
Though I'd actually argue that if we export an object, app scripts could potentially run async tasks in parallel so if we'd have more than one property that evaluates to a promise/observable, it could run all of them at once and complete when all are done (something like a
Promise.all([ ... ])/Observable.merge(...)).Yet, the user could do this as well, but if app scripts would do it, it would spare the user of adding extra implementation.
I guess there are many ways this can be tackled, but the simpler the better.
fiznool commentedon Feb 17, 2017
ehorodyski commentedon Feb 17, 2017
I like where @rolandjitsu is going, but instead of tying it down to a specific implementation, is there a way you can take the environment path being used from
package.jsonin theionic_envobject, and then alias it, so it'simport { <T> } from @ionic/configorimport { <T> } from @ionic/env?I don't know how the Angular library does aliasing so you can do
import { HTTP } from '@angular/http', instead ofimport { HTTP } from 'angular/modules/wherever/it/lives/http', but that's how I'd implement it.Give the users the ultimate control of building what they want to export from their environment/config files, but provide a way for those paths to be swapped out during building, and I think properly creating a module alias, which I don't know how to do, is the best approach.
danbucholtz commentedon Feb 17, 2017
If we were to expose a hook and allow the user to load in async values, perhaps we could do something like this:
Those modules could then export a function that returns a
Promise. That way it will always be async.It could work like this:
Something like this would work in the vast majority of use cases.
In an application's code, let's say you need to hit a different HTTP service for development and production.
You could write a service like this:
Your implementation to replace it could look like this:
ehorodyski commentedon Feb 17, 2017
@danbucholtz - I think that is really over-complicated.
Take a look at Webpack's resolve aliasing. This could be done dynamically when starting
ionic serveor the other scripts, depending on theenvvariable:The only implication to the user is that they'd need to store their config files outside the folder with their source code, as to not include all the files defined. Or maybe not, you can run a glob that excludes the other environment files not being used. Plus, there's no resolution during application running.
josh-m-sharpe commentedon Feb 17, 2017
For us this isn't necessarily just about env=dev/staging/prod. For some context, we're coming to ionic(v2) from a vanilla cordova app and we use the same codebase to generate multiple different apps primarily distinguished by an 'org_id'. (The app passes this value in server calls to receive different content, amongst a bunch of other differences). We also currently inject the internal and external version numbers since they vary (inconsistently) by org_id.
So, in a nutshell, just passing in "environment" wouldn't solve this problem for us. Why not make this feature align better with unix best practices and simply make all of the current env available inside the application somehow?
for example:
ORG_ID=123 ENVIRONMENT=staging ionic serve
For what it's worth, cordova (or node?) is doing this already automatically. That is, you can access 'process' inside a cordova hook without having to require anything. From that, it's just process.env.ORG_ID == '123'
rolandjitsu commentedon Feb 17, 2017
@danbucholtz I agree, that'd be a reasonable solution. And I'm sure that it would cover most use cases.
@ehorodyski I think it's already possible to use aliasing if you use your own webpack config file (I cannot confirm it, never tried it). But I do see what you mean, though that would not work if you have async operations that need to run in order to compute the env values you want to have available in the app. It would also not work for the use case @josh-m-sharpe describes where you need some env vars that are not exposed by app scripts.
@josh-m-sharpe using the solution proposed would also solve what you're referring to. You'd just need to expose from
process.env:I think it's essential to have a more generic and universal solution, such as the one proposed by @danbucholtz in #762 (comment), that can cover most of the uses cases since the dev needs vary as we can see from the posts on this topic.
biesbjerg commentedon Feb 17, 2017
Am I the only one that really wants hinting of config keys, e.g. by defining a ConfigInterface? I have not seen it mentioned and I'm not sure how to do it elegantly, though...
ehorodyski commentedon Feb 18, 2017
@biesbjerg - Right, this is what I'd like accomplished as well. I need to brush up on how to do Typescript module aliasing, so that the paths can be dynamically generated when you run
ionic serve.If
ionic-app-scriptsdoesn't want to implement something like this, I think it would be great to use for yourself. It's really not hard, I've done it before.95 remaining items
ramonornela commentedon Jan 2, 2018
@danbucholtz can apply a solution similar to https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#adding-custom-environment-variables, following https://12factor.net/config see too: https://www.npmjs.com/package/dotenv.
GFoley83 commentedon Feb 22, 2018
@emcniece @gshigeto Do your solutions support using a custom environment file e.g.
environment.test.tswhen usingngc? If not what modification would be needed?I'd like to be able to build APKs for the various environments e.g.
ionic cordova build android --test.emcniece commentedon Feb 22, 2018
@GFoley83 Yes, AOT (
ngc) compilation works well with this pattern.The downside of the provided example is that "production" builds end up with double flags, but that's not the end of the world. Here's a sample of my
package.jsonscripts:The
--releaseand--prodflags are for Ionic. The--env=prodis the custom flag for the provided example Webpack config modification, which matches the./src/environments/environment.prod.tsfile. Using--prodor--releasecompiles the code withngc, not sure exactly which one.Oh, again as a disclaimer, that is totally not "my" solution, it came from William Ghelfi.
murraybauer commentedon Feb 22, 2018
GFoley83 commentedon Feb 22, 2018
I ended up using a combo of @emcniece and @gshigeto solutions, so massive thanks to them.
I wanted to have environment variables work in Ionic exactly like how they do in Angular CLI (especially given Ionic 4 is somewhere on the horizon), whilst also supporting Karma and Protractor tests.
To use the environment variables, just add
import { environment } from '@env/environment';.Also supports
ngcso I can build an Android APK with any environment config e.g. myenvironment.test.tsconfig.This solution also supports using
ionic servewith any of your configurations e.g.ionic serve --env=prodI've managed all this with the following setup:
/src/app/environments folder contains
/tsconfig.json
{ "compilerOptions": { "allowSyntheticDefaultImports": true, "baseUrl": "./src", "declaration": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "paths": { "@env/*": [ "environments/*" ] }, "lib": [ "dom", "es2016" ], "module": "es2015", "moduleResolution": "node", "sourceMap": true, "target": "es5" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules", "src/**/*.spec.ts" ], "typeRoots": [ "node_modules/@types" ], "compileOnSave": false, "atom": { "rewriteTsconfig": false } }/config/webpack.config.js
/test-config/webpack.test.js
/package.json
raajmayukh commentedon Mar 15, 2018
@keithdmoore Thanks for your idea to fix this solution. I have followed your solution and able to load files as per what's been set as fileName. But with this solution is it possible to access process.argv.env in TS files anywhere in the application?
I need to access them in my app to load some Mock services for different environments. Earlier(Angular 4 and ionic app scripts 1.x) i was achieving this by setting process.argv.NODE_ENV. I was using Opaque token for the same. Now with Angular 5 and ionic app scripts 3.1.x i am using Injection token and trying to access process.argv.env together with your solution but it always comes as undefined in TS files. Any idea on this?
I had created an issue earlier in Ionic repo, probably should have created here: Here is the link with all info:
[(https://github.com/ionic-team/ionic-framework/issues/14150)]
keithdmoore commentedon Mar 16, 2018
I’m sure you could. I followed someone else’s suggestion above. I have a name attribute in my environment model that is the same as what is in the file name. I can access the name in my ts files if I need to.
tabirkeland commentedon Mar 16, 2018
All, with Ionic 4 release approaching, I know that ENV vars will be handled. If you are using Ionic 3.9.2, here is what I have been using for months to handle ENV vars. It's been pieced together from this and a few other threads.
https://gist.github.com/tabirkeland/a17c67b2f1ea3331d94db34ed7191c34
writer0713 commentedon Apr 2, 2018
made a starter project with detail explanations.
https://github.com/writer0713/ionic-environment-setting/blob/master/README.md
tabirkeland commentedon Apr 3, 2018
@writer0713 nice one. So I assume my gist helped?
writer0713 commentedon Apr 4, 2018
@tabirkeland
Yes, I read so many different articles, but nothing worked. After I followed your code, it worked. Thanks.
daraul commentedon May 22, 2018
@writer0713 your readme was a life saver. Worked like a charm
Thanks to you and @tabirkeland
cleverappdesign commentedon Oct 12, 2018
@writer0713 @tabirkeland thanks!! It works so well!
sana-moussa commentedon Dec 7, 2018
this is the only efficient solution that worked for me, thanks!
vdias38 commentedon Jan 16, 2019
@GFoley83 I've tested your solution but with AOT in specific cases it doesn't work, I ignore the reason.
How to reproduce the error:
ionic build --env=prod --prodIt's annoying if you use firebase and need to initiate it with env vars on your app.module (
AngularFireModule.initializeApp(ENV.firebase)). At the moment I didn't find a good solution. @writer0713 suggest to rewrite env file using npm hooks, I'll check it.