Feature request: Ionic 2 (dev/prod) environment variables configuration
From @amreladawy on July 24, 2016 6:58
Short description of the problem:
It is a feature request. Just like Angular2, I hope that Ionic can provide 2 files (environment.dev.ts and environment.prod.ts) that would contain variables with different values corresponding to production and development environment. During the build, the appropriate file to be copied and bundled within the app artifact.
Which Ionic Version? 2.x
https://forum.ionicframework.com/t/ionic-2-environment-variables-config-setup/58147/1
https://stackoverflow.com/questions/36004810/how-to-config-different-development-environment-in-angular-2-app
Copied from original issue: driftyco/ionic#7413
I implemented the solution from @fiznool the webpack script does not look for env/dev.json but env/dev and when it does have .json it auto converts to an object so no need for the JSON.parse. I changed envVars = JSON.parse(require(path.join(projectRootDir, 'env', env))); to envVars = require(path.join(projectRootDir, 'env', env + '.json'));.
My very limited knowlege of webpack stumped me for a bit and I had to add extra quotes in my json so I ended up with {"foo": "\"bar\""}. There is probably a better way to deal with this though.
Since Ionic 2.0 final is out, I'm guessing there will be many more production level apps starting out.
If we can get an update from the Ionic team about this feature, we can at least know if we need to implement a temporary solution or go all in using one of the various suggestions from the comments.
so fyi i was able to implement @fiznool suggestion along with @NightOnFire changes and it worked for me. That said, pay attention to @NightOnFire comments on how to set up entries in your json file.
{"foo": "bar"} WILL NOT WORK and will generate exceptions. you HAVE to format your json entries the same way @NightOnFire did his.
Hope this helps.
@NightOnFire @coldAlphaMan thanks for your comments, I've updated my comment to reflect these needed changes. :+1:
You cannot useENV in app.module.ts in production using @fiznool method. Any solution for this?
@geraneum Use Rollup with rollup-plugin-replace and replace strings instead of variables:
replace({
values: {
'{{IONIC_ENV}}': process.env.IONIC_ENV,
},
exclude: 'node_modules/**'
}),
And somewhere in your app:
const env = '{{IONIC_ENV}}';
@geraneum could you share a code snippet that shows this issue? It might be possible to split the references to ENV out into separate exported functions or constants to allow for aot builds.
@fiznool
I have put declare const ENV; in /src/declarations.d.ts
Then in /env/prod.json I have something like this:
{
"ionicCloudAppId": "'<APP ID>'",
}
in /src/app/app.module.ts I have:
const cloudSettings: CloudSettings = {
'core': {
'app_id': ENV.ionicCloudAppId
}
}
Everything else is the same as what you've suggested.
I have other variables declared in prod.json and they work everywhere except app.module.ts.
Also using ENV.ionicCloudAppId in other places works.
This only happens with --prod flag.
AOT can be fiddly. What exactly is the error message?
I've previously had luck exporting constants so that AOT works correctly, you could try this.
export const cloudSettings: CloudSettings = {
'core': {
'app_id': ENV.ionicCloudAppId
}
}
@fiznool added export still getting the same error:
Cannot read property 'ionicCloudAppId' of undefined
Also how can I use this feature with ionic package build --release? when I do that, dev settings gets picked up in the generated APK, I also provided release.json, but still no luck.
@geraneum I just created a sample repo and building for production works as expected. In app.module.ts, there is a console log which prints the variable ENV.api_server to the console. This is defined differently in dev.json and prod.json.
When running ionic run android --prod I see the following in logcat:
02-11 14:16:26.883 16383 16383 I chromium: [INFO:CONSOLE(32)] "http://prod.example.com", source: file:///android_asset/www/build/main.js (32)
which is what I would expect.
Perhaps you can use this repo and see what the differences are in your own app? Here is my ionic info:
Cordova CLI: 6.5.0
Ionic Framework Version: 2.0.1
Ionic CLI Version: 2.2.1
Ionic App Lib Version: 2.2.0
Ionic App Scripts Version: 1.0.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.8
Node Version: v6.9.4
Xcode version: Not installed
Regarding the release build, you still need the --prod flag, AFAIK --release is purely concerned with generating release keys to sign your app with.
ionic package build --prod --release
@fiznool Thank you very much for your help.
I got the correct output from console log... but for test I changed the app.module.ts like this:
imports: [
IonicModule.forRoot(MyApp, {
tabsHideOnSubPages: ENV.tabsHideOnSubPages
})
],
and prod.json to this:
{
"api_server": "'http://prod.example.com'",
"tabsHideOnSubPages": true
}
And as soon as I did it, I got the following error on app launch:
Uncaught TypeError: Cannot read property 'tabsHideOnSubPages' of undefined
at e.createInternal (main.js:26)
at e.create (main.js:11)
at t.create (main.js:11)
at main.js:7
at t.invoke (polyfills.js:3)
at Object.onInvoke (main.js:4)
at t.invoke (polyfills.js:3)
at e.run (polyfills.js:3)
at t.run (main.js:4)
at e._bootstrapModuleFactoryWithZone (main.js:7)
Yes, I see now. Seeing the same issue. Maybe someone with more aot knowledge can help as I'm a bit stumped too :smile:
I was seeing the problem of undefined things after creating config files like rollup.config.js and updating package.json. It is important to copy the files from app-scripts on git hub and edit them rather than create new files because you are overriding the defaults, which breaks if things are missing.
For the initial problem, I wanted to contribute my problem and solution:
I think the support is already there. I wanted to avoid storing the api keys and other identities from source control. I did the following:
-
Create a "config" folder and an "environment" folder under the app root.
-
Copy the default ionic app-script for the copy config from https://github.com/driftyco/ionic-app-scripts/blob/master/config/copy.config.js to /config
-
Edit the copy.config.js (for me it was a firebase config, which I placed before polyfills):
... copyFonts: { src: ['{{ROOT}}/node_modules/ionicons/dist/fonts/**/*', '{{ROOT}}/node_modules/ionic-angular/fonts/**/*'], dest: '{{WWW}}/assets/fonts' }, copyFirebaseConfig: { src: ['{{ROOT}}/environment/firebase-config.js'], dest: '{{BUILD}}' } , copyPolyfills: { src: ['{{ROOT}}/node_modules/ionic-angular/polyfills/polyfills.js'], dest: '{{BUILD}}' }, ... -
Add the config to package.json so that ionic build knows that the default is overridden:
... "config": { "ionic_copy:": "config/copy.config.js" }, ... -
Add a file which exports the desired config as a const at the location specified in the modified copy.config.js
-
Import the config where it is needed (for me it's a single import in app.module.ts):
import {FirebaseConfig} from '../../environment/firebase-config'; -
Tell git to ignore everything under "environment"
-
Tell your build server to add the config file to its working dir under subdir "environment" (I haven't done this yet)
Now only your build server and dev environment know what your api keys are. I hope this helps somebody else.
@domlogic But doing so I can not get a configuration file for environments, right? Example, firebase.dev.ts, firebase.prod.ts etc ...
@jhonathas you don't need to manage that in the app code, just one environment for dev which you can use locally. Because it's not checked into source control, you can have a build server provide the prod config in the same location with the same name (but in its own workspace) and that one will be used instead. Also, other developers can provide their own config and work isolated from you if they provision their own resources for development (eg- a different firebase). I feel like these configurations are a dev ops concern rather than app dev.
Inspired by the solution of @dnmd I updated the rollup config a little bit in order to make it work with multiple ts-config files. It's supporting live reload, build and run commands of Ionic. I just copied most of the description from @dnmd, thanks mate. ;-)
Implementation steps
install the rollup-plugin-replace
npm install --save-dev rollup-plugin-replace
Create as many config files you want; environment.dev.ts, environment.qa.ts, environment.production.ts within e.g. the src/config directory.
├── src/config/environment.dev.ts
export const ENV = {
PRODUCTION : false,
API_URL : 'dev.local'
};
├── src/config/environment.qa.ts
export const ENV = {
PRODUCTION : false,
API_URL : 'qa.local'
};
├── src/config/environment.production.ts
export const ENV = {
PRODUCTION : true,
API_URL : 'prod.local'
};
import the environment-dev as the default within your pages / services etc., as the rollup config will look for the environment.dev to be replace with the targeted environment.
// use the 'environment.dev' as the default import(!)
import { ENV } from '../../config/environment.dev';
@Component({
templateUrl: 'hello-ionic.html'
})
export class HelloIonicPage {
console.log( ENV.API_URL );
}
Update your /package.json
├── /package.json
"config": {
"ionic_rollup": "./config/rollup.config.js"
}
create your rollup.config.js within the /config directory. Require the plugin, and add the replace snippet below to your plugins section. One can use node_modules@ionic\app-scripts\config\rollup.config.js as a template.
├── /config/rollup.config.js
var replace = require('rollup-plugin-replace');
// Read environment from passed parameter.
var env = 'config/environment.dev';
env = (argv.dev !== undefined) ? 'config/environment.dev' : env;
env = (argv.production !== undefined) ? 'config/environment.production' : env;
env = (argv.qa !== undefined) ? 'config/environment.qa' : env;
...
plugins: [
replace({
exclude: 'node_modules/**',
'config/environment.poc': env
}),
...
]
We still got the risk of outdated rollup configuration whenever Ionic releases an update. But for now it's working fine for us.
I tried the solution of @dnmd.. I am getting rollup failed: Cannot read property 'file' of undefined. Any help? Thanks.
Another smart solution here -> https://github.com/driftyco/ionic-app-scripts/pull/683 (using webpack alias) 😉
I am going to move this thread to driftyco/ionic-app-scripts because any updates to accomplish this would be in that codebase.