ionic-cli icon indicating copy to clipboard operation
ionic-cli copied to clipboard

Feature request: Ionic 2 (dev/prod) environment variables configuration

Open jgw96 opened this issue 10 years ago • 121 comments

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

jgw96 avatar Jul 25 '16 20:07 jgw96

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.

itrethan avatar Oct 22 '16 08:10 itrethan

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 process.env.IONIC_ENV variable during compile time. This will use the environment.dev.ts during development and environment.prod.ts when in production.

Implementation steps

  1. install the rollup-plugin-replace npm install --save-dev rollup-plugin-replace

  2. create two files; environment.dev.ts and environment.prod.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.prod.ts

export const ENV = {  
  PRODUCTION : true,
  API_URL    : 'prod.local'
};
  1. import the environment-dev as the default within your pages / services etc.
// 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 );
}
  1. update your /package.json
├── /package.json

"config": {
    "ionic_rollup": "./config/rollup.config.js"
}
  1. 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');
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

dnmd avatar Oct 24 '16 13:10 dnmd

Is there any plans to actually implement this?

ghost avatar Oct 26 '16 14:10 ghost

With "@ionic/app-scripts": "0.0.39" now defaulting to webpack for bundling, I am doing something like this.

Steps to implement:

  1. Make sure you have installed the latest app-scripts npm install @ionic/app-scripts@latest and have the latest tsconfig.json.

  2. Install dotenv.

  3. Create .env file with env variables defined in the root directory of your app. Recommended: add .env to .gitignore.

  4. Create and modify webpack.config.js from original found here:

├── /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;
}
...
  1. Define custom webpack config file in package.json.
├── /package.json

"config": {
    "ionic_webpack": "./config/webpack.config.js"
}
  1. Create custom typings file defining the constants that are in your .env file so that webpack can populate them and you are able to reference them in your application.
├── /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 .env files for different environments and require them in webpack.config.js like so:

require('dotenv').config({path: '/custom/path/to/your/env/vars'})

tabirkeland avatar Nov 01 '16 17:11 tabirkeland

This solution is working, but I think, rewriting all webpack.config is not good, becase updates... Is there any idea from ionic team?

tomasstankovic avatar Nov 08 '16 09:11 tomasstankovic

@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 :/

rossholdway avatar Nov 11 '16 11:11 rossholdway

I'd really like to see this functionality supported. Is a custom webpack config the only way?

locnguyen avatar Nov 11 '16 15:11 locnguyen

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 runionic serve with production environment. I have set an environment.ts in the root folder of the app that contains all the variables.

environment.ts

export class ENV {

    public static currentEnvironment: string = "development";
    // public static currentEnvironment: string = "production";

    public static development: any = {
         key1: "value1",
         key2: "value2",
        ......
        ......
    };
    public static production: any = {
        key1: "value1",
        key2: "value2",
        ......
        ......
    };
}

Then I added an environment.service among my services.

environment.service.ts

import {Injectable} from '@angular/core';
import {ENV} from '../../environments/environment';

@Injectable()
export class EnvironmentService {


    public getKey1() : string{
        if(ENV.currentEnvironment === "development"){
            return ENV.development.key1;
        } else if(ENV.currentEnvironment === "production") {
            return ENV.production.key1;
        }
    }

    public getKey2() : string{
        if(ENV.currentEnvironment === "development"){
            return ENV.development.key2;
        } else if(ENV.currentEnvironment === "production") {
            return ENV.production.key2;
        }
    }

     ......
     ......

}

Then I added the service to the providers of the app.module and used it like any other service. E.g. in any component you can access the values like this:

any.component.ts

...
...
...

import {EnvironmentService} from '../../services/environment.service';

...
...
...

constructor(
                      ...
                      ...
                      ...
                      private environmentService: EnvironmentService
                      ...
                      ...
                      ...) {
    }

...
...
...

let baseUrl = this.environmentService.getKey1();

...
...
...

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. E.g. : ionic (serve/run) (--prod/--dev)

ghost avatar Nov 11 '16 16:11 ghost

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

ionic serve / PRODUCTION or CUSTOM ENV: $ ionic serve --env=prod, $ ionic serve --env=test, $ ionic serve --prod

ionic build / PRODUCTION ENV (DEFAULT): $ ionic build

ionic build / DEVELOPMENT or CUSTOM ENV: $ ionic build --dev $ ionic build --env=test $ ionic build --env=dev

eg. http://jonnyreeves.co.uk/2016/simple-webpack-prod-and-dev-config/

tomasstankovic avatar Nov 11 '16 17:11 tomasstankovic

@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. I'm actually using this in a corporate project with a big number of people on the team. I think nowadays every team uses version control systems like git or svn. So, this would be just a matter of team functionality and team members being coordinated with each other. And furthermore, there is usually only one person in team who is in charge of deploying the app. But, again, you're right. With manual toggle of environments, there is a slightly higher chance of making the mistake. So, as I said, this is only a temporary fix. Ideally, this should be internal to ionic, using the commands you mentioned.

ghost avatar Nov 11 '16 17:11 ghost

+1

allaanz avatar Nov 14 '16 19:11 allaanz

Hey, guys, any progress of official implements?

zjhiphop avatar Nov 20 '16 11:11 zjhiphop

@dnmd can you confirm that your solution works with a production build?

rolandjitsu avatar Nov 21 '16 15:11 rolandjitsu

with 0.0.46 adding anything at config in package.json trigger rollup warnings (and the script freeze after that)

[18:58:40]  rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
            re-exports 'NgContentAst' from both
            /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
            ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.
[18:58:40]  rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
            re-exports 'PropertyBindingType' from both
            /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
            ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.
[18:58:40]  rollup: Conflicting namespaces: /space/www/applications/wav/node_modules/@angular/compiler/index.js
            re-exports 'templateVisitAll' from both
            /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js (will be
            ignored) and /space/www/applications/wav/node_modules/@angular/compiler/src/template_parser/template_ast.js.

By the way, isn't it better to listen for the argument --release ? Another thing, why with 0.0.46 it's rollup and not webpack by default?

Yimiprod avatar Nov 25 '16 18:11 Yimiprod

I like the idea of @slinto In our case, we have actually 5 environments...

  • dev
  • test (unit test)
  • iat (human first line test => developer tester)
  • uat (human second line test => business client tester)
  • prod

And we have to copy config file at build time to choose the environment. To chose the environment at build time, we run it like : TARGET=xxx ionic run yyy for mac or set TARGET=xxx&& ionic run yyy for windows developer.

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!

movrack avatar Nov 26 '16 15:11 movrack

Definitely a must. So +1

rmx48 avatar Nov 28 '16 08:11 rmx48

So how would this tie in with the Live Deploy to channel feature currently available https://docs.ionic.io/services/deploy/ ?

iacomus avatar Nov 30 '16 18:11 iacomus

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 env-configuration.json located in the www folder before anything else (so that your api url will be set even in your apiService constructor, for example).

In the package documentation, I linked a simple node executable to easily copy the configuration file for a specific environment.

Advantages

  • You don't need to override the Ionic webpack.config (which could break things when Ionic updates).
  • You can have as much environments as you want and name it as you like.
  • You can dynamically change the configuration file without having to recompile the app (which will be very useful for continous integration systems).

Hope this will help.

mvidailhet avatar Dec 21 '16 14:12 mvidailhet

Any updates to this Ionic team? I would love to see this baked into the ionic-app-scripts repo.

sean-hill avatar Jan 02 '17 17:01 sean-hill

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:

  • The Ionic webpack.config script is built upon, not replaced, meaning that any updates to @ionic/app-scripts should be merged in.
  • The script is aware of Ionic's --prod flag, allowing you to provide separate configuration for dev and prod builds.
  • There is no dependency on dotenv.

Here's the steps to get it all working:

  1. Create a file at config/webpack.config.js and paste the following content:
// 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;
  1. Add the following entry to your package.json:
  "config": {
    "ionic_webpack": "./config/webpack.config.js"
  }
  1. If you need additional configuration, create two files env/dev.json and env/prod.json. In here, put any configuration you need for that environment. Your json should be an object of key-value pairs, which will be made available for use in your application.
{
  "enableLogging": true,
  "apiServerUrl": "\"http://example.com/api\""
}

Now, you can use the ENV global constant anywhere in your .ts files:

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 ENV object with a single key, environment, which is set to prod if you run your ionic command with the --prod flag. Otherwise, this will be dev.

The env/dev.json and env/prod.json files are optional. If present, the script will merge the appropriate object into ENV. The script above uses webpack's DefinePlugin, so remember to 'stringify' any string values, otherwise webpack will assume you want to insert a code fragment. For example:

{
  "apiServerUrl": "\"http://example.com/api\""
}

It would be great to see this baked into the core webpack.config.js file in the app-scripts repo.

fiznool avatar Feb 02 '17 11:02 fiznool