-
Notifications
You must be signed in to change notification settings - Fork 311
Feature request: Ionic 2 (dev/prod) environment variables configuration #760
Comments
From @itrethan on October 22, 2016 8:48 Can we raise the priority for this issue? This is actually very important. Our app has different configs for prod and devel. Without this, it requires ugly hand rolled variable updates... Just make the release really cumbersome. |
From @dnmd on October 24, 2016 13:46 Currently our implementation uses the rollup-plugin-replace, and a slightly modified rollup config. Basically what happens is that the import paths are replaced based on the Implementation steps
├── src/config/environment.dev.ts
export const ENV = {
PRODUCTION : false,
API_URL : 'dev.local'
}; ├── src/config/environment.prod.ts
export const ENV = {
PRODUCTION : true,
API_URL : 'prod.local'
};
// 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 );
}
├── /package.json
"config": {
"ionic_rollup": "./config/rollup.config.js"
}
├── /config/rollup.config.js
var replace = require('rollup-plugin-replace');
var isProd = (process.env.IONIC_ENV === 'prod');
...
plugins: [
replace({
exclude: 'node_modules/**',
// use the /config/environment-dev as the default import(!), no stub needed.
// note we only replace the "last" part of the import statement so relative paths are maintained
'/config/environment-dev' : ( isProd ? '/config/environment-prod' : '/config/environment-dev'),
})
...
] Hope this helps someone! Of course in an ideal situation a file replacement would take place, similar to the Angular CLI |
From @Maziar-Fotouhi on October 26, 2016 14:55 Is there any plans to actually implement this? |
From @tabirkeland on November 1, 2016 17:36 With Steps to implement:
├── /config/webpack.config.js
require('dotenv').config();
...
function getPlugins() {
var plugins = [
new webpack.DefinePlugin({
'API_URL': JSON.stringify(process.env.API_URL)
// Add any more variables here that you wish to define
})
];
if (process.env.IONIC_ENV === 'prod') {
// This helps ensure the builds are consistent if source hasn't changed:
plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
}
return plugins;
}
...
├── /package.json
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
├── /src/customTypings/customTypings.d.ts
declare var API_URL: string;
// Add any more variables here that you wish to define You should now be able to reference the global variable(s) in your app. Furthermore, you can create multiple require('dotenv').config({path: '/custom/path/to/your/env/vars'}) |
From @slinto on November 8, 2016 9:41 This solution is working, but I think, rewriting all webpack.config is not good, becase updates... Is there any idea from ionic team? |
From @rossholdway on November 11, 2016 11:13 @jgw96 Can we get this added to a milestone? We should be able to specify different environment configuration e.g. different API endpoints for dev and production. As @slinto mentioned creating a modified webpack.config is not ideal as updates will cause issues :/ |
From @locnguyen on November 11, 2016 15:54 I'd really like to see this functionality supported. Is a custom webpack config the only way? |
From @Maziar-Fotouhi on November 11, 2016 16:10 Okay... After a lot of coffee and head bumping, I've realized that the best way (at least for me) is to change the environments manually and not rely on ionic to change it. That was mainly because ionic-cli does not let you run environment.ts
Then I added an environment.service among my services. environment.service.ts
Then I added the service to the providers of the app.module and used it like any other service. any.component.ts
And finally, in order to change the environment, you have to toggle (comment and uncomment) the first two line of environment.ts. This is a good workaround for now, if you need different values (URLs, API keys, etc.) to be used in development and production. But, I think eventually, ionic and ionic-cli teams will have to work together to integrate something like this internally, that lets us use different sets of environment variables based on a flag that we pass to the command that is running the app. |
From @slinto on November 11, 2016 17:13 hmm, the manual comment/uncomment of right ENV is dangerous, because is there a big risk with publishing application with development environment to store, especially if your team is about 1+ people :) I think about right way as: ionic serve / DEVELOPMENT ENV (DEFAULT): ionic serve / PRODUCTION or CUSTOM ENV: ionic build / PRODUCTION ENV (DEFAULT): ionic build / DEVELOPMENT or CUSTOM ENV: eg. http://jonnyreeves.co.uk/2016/simple-webpack-prod-and-dev-config/ |
From @Maziar-Fotouhi on November 11, 2016 17:31 @slinto You are absolutely correct, there is the possibility of publishing the app with dev variables. But, it is only as dangerous as any other solution. You may build the prod app with the wrong command as well. |
From @allaanz on November 14, 2016 19:57 +1 |
From @zjhiphop on November 20, 2016 11:16 Hey, guys, any progress of official implements? |
From @rolandjitsu on November 21, 2016 15:2 @dnmd can you confirm that your solution works with a production build? |
From @Yimiprod on November 25, 2016 18:4 with
By the way, isn't it better to listen for the argument |
From @movrack on November 26, 2016 15:17 I like the idea of @slinto
And we have to copy config file at build time to choose the environment. This is managed by a hook based on this post : http://www.kdmooreconsulting.com/blogs/build-a-cordova-hook-to-setup-environment-specific-constants/ But since we do that, we lost the live reload feature! (ionic-app-script watch doesn't copy our right config.js file and we don't know how to do that). If we can set a parameter like @slinto told -- to choose the environment with something like "--env=xxx", and make it available for live reload ... -- it will be really cool! |
From @schaergeek on November 28, 2016 8:44 Definitely a must. So +1 |
From @iacomus on November 30, 2016 18:56 So how would this tie in with the Live Deploy to channel feature currently available https://docs.ionic.io/services/deploy/ ? |
From @mvidailhet on December 21, 2016 14:16 OK, so I needed this kind of feature to be able to have different parameters (api endpoints, google analytics ID etc...) with different environments (dev, preprod, prod...). So I made my first module (feedbacks more than welcome, and please be gentle :p) to be able to do that: gl-ionic2-env-configuration Basically, it loads a In the package documentation, I linked a simple node executable to easily copy the configuration file for a specific environment. Advantages
Hope this will help. |
From @sean-hill on January 2, 2017 17:49 Any updates to this Ionic team? I would love to see this baked into the |
From @fiznool on February 2, 2017 11:39 Inspired by the solution from @tabirkeland I thought I'd post my own version of this. The differences with the script below vs the original solution:
Here's the steps to get it all working:
// Set the `ENV` global variable to be used in the app.
var path = require('path');
var webpack = require('webpack');
var projectRootDir = process.env.IONIC_ROOT_DIR;
var appScriptsDir = process.env.IONIC_APP_SCRIPTS_DIR;
var config = require(path.join(appScriptsDir, 'config', 'webpack.config.js'));
var env = process.env.IONIC_ENV || 'dev';
var envVars;
try {
envVars = require(path.join(projectRootDir, 'env', env + '.json'));
} catch(e) {
envVars = {};
}
config.plugins = config.plugins || [];
config.plugins.push(
new webpack.DefinePlugin({
ENV: Object.assign(envVars, {
environment: JSON.stringify(env)
})
})
);
if(env === 'prod') {
// This helps ensure the builds are consistent if source hasn't changed:
config.plugins.push(new webpack.optimize.OccurrenceOrderPlugin());
}
module.exports = config;
"config": {
"ionic_webpack": "./config/webpack.config.js"
}
{
"enableLogging": true,
"apiServerUrl": "\"http://example.com/api\""
} Now, you can use the declare const ENV;
if(ENV.environment === 'dev') {
// Run without the `--prod` flag.
// Any keys defined in `dev.json` will be available on the `ENV` object.
} else if (ENV.environment === 'prod') {
// Run with the `--prod` flag.
// Any keys defined in `prod.json` will be available on the `ENV` object.
} The script creates an The {
"apiServerUrl": "\"http://example.com/api\""
} It would be great to see this baked into the core |
From @NightOnFire on February 2, 2017 18:6 I implemented the solution from @fiznool the webpack script does not look for 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 |
From @swaheed2 on February 2, 2017 19:39 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. |
From @coldAlphaMan on February 3, 2017 23:14 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. Hope this helps. |
From @fiznool on February 4, 2017 7:47 @NightOnFire @coldAlphaMan thanks for your comments, I've updated my comment to reflect these needed changes. 👍 |
From @rolandjitsu on February 11, 2017 11:32 @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}}'; |
From @geraneum on February 11, 2017 12:58 I have put Then in
in
Everything else is the same as what you've suggested. |
From @fiznool on February 11, 2017 13:37 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.
|
From @geraneum on February 11, 2017 13:54 @fiznool added Also how can I use this feature with |
From @fiznool on February 11, 2017 14:21 @geraneum I just created a sample repo and building for production works as expected. In When running
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
Regarding the release build, you still need the
|
From @geraneum on February 11, 2017 14:50 @fiznool Thank you very much for your help.
and
And as soon as I did it, I got the following error on app launch:
|
From @fiznool on February 11, 2017 16:19 Yes, I see now. Seeing the same issue. Maybe someone with more aot knowledge can help as I'm a bit stumped too 😄 |
From @domlogic on February 14, 2017 9:2 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:
Now only your build server and dev environment know what your api keys are. I hope this helps somebody else. |
From @jhonathas on February 15, 2017 19:16 @domlogic But doing so I can not get a configuration file for environments, right? Example, firebase.dev.ts, firebase.prod.ts etc ... |
@jthoms1 see this starter https://github.com/mbamobi/ionic2-starter created where I am working Thanks |
What does everyone think of something like this? Thanks, |
+1 |
Inspired by the @dnmd and Angular 2 solution, I've only made minor changes, and it works fine. Implementation stepsInstall the rollup-plugin-replacenpm install --save-dev rollup-plugin-replace Create this files in the
|
thanks @RodolfoSilva for that example! This is my version without the need of
const rollupConfig = require('@ionic/app-scripts/config/rollup.config');
const replace = require('rollup-plugin-replace');
const isProd = (process.env.NODE_ENV === 'prod');
if (isProd) {
console.log('Building with Prod enviroment');
} else {
console.log('Building with Dev enviroment. Set NODE_ENV=prod for production API URL, etc.');
}
const rollupConfigReplaceEnviroment = replace({
exclude: 'node_modules/**',
ENVIRONMENT: isProd ? 'prod': 'dev'
});
rollupConfig.plugins = rollupConfig.plugins || [];
rollupConfig.plugins.splice(0, 0, rollupConfigReplaceEnviroment);
module.exports = rollupConfig; Then you just need to add this in
let ENV = 'ENVIRONMENT'; // <-- this text will be replaced by the 'rollup-plugin-replace' module
const isProd = (ENV == 'prod');
let PROTOCOL;
let API_URL;
if (isProd) {
PROTOCOL = 'https:';
API_URL = 'api.example.com';
} else {
PROTOCOL = 'http:';
API_URL = 'dev.example.com'; // maybe pointing to localhost
} And now you run it like this 🎉 : $ ionic serve --nobrowser
> ionic-hello-world@ ionic:serve MyMobileApp
> ionic-app-scripts serve "--v2" "--nobrowser" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
[00:07:25] ionic-app-scripts 1.1.3
[00:07:25] watch started ...
[00:07:25] build dev started ...
[00:07:25] clean started ...
[00:07:25] clean finished in 5 ms
[00:07:25] copy started ...
[00:07:25] transpile started ...
Building with Dev environment. Set NODE_ENV=prod for production API URL, etc. or for prod: $ NODE_ENV=prod ionic serve --nobrowser
> ionic-hello-world@ ionic:serve MyMobileApp
> ionic-app-scripts serve "--v2" "--nobrowser" "--address" "0.0.0.0" "--port" "8100" "--livereload-port" "35729"
[00:01:31] ionic-app-scripts 1.1.3
[00:01:31] watch started ...
[00:01:31] build dev started ...
[00:01:31] clean started ...
[00:01:31] clean finished in 2 ms
[00:01:31] copy started ...
[00:01:31] transpile started ...
Building with Prod environment
... |
@RodolfoSilva @gianpaj I am getting error "rollup failed: Unexpected token" any ideas what it could be? |
@vovikdrg do you by chance use I'm not sure why though. |
@rolandjitsu yes i am... |
@rolandjitsu thanks for pointing out, I have found issue. It was dependency to old rxjs. |
What's the official solution for this? |
From @jgw96 on July 25, 2016 20:42
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: ionic-team/ionic-framework#7413
Copied from original issue: ionic-team/ionic-cli#1205
The text was updated successfully, but these errors were encountered: