(designed for ionic2)
- Config files in either .js or .json (if both are found the .js config will be prioritized)
- Creates a provider file in src/providers/app-config.ts when this script is ran
- Access to enviornment variables through use of the .js file as a config
- Place the script found at
./scripts/replace.env.js
in your project inside of a scripts folder (create one if it does not exist). - Add the following commands to your package.json file inside of your scripts section:
"preionic:build": "node ./scripts/replace.env",
"preionic:serve": "node ./scripts/replace.env",
"generate-env": "node ./scripts/replace.env",
-
Create an env folder in your project and create files for your different evnironments named the way you want to refer to them in the command line. For example: production.js can be targeted with
--env p
-
Import/inject the provider in your app.modules.ts as you would with any other provider (use this file path:
../providers/app-config
) -
Create your environment object and fill it with what you need
-
Import the module in any other ts file(s) you want to use it in.
-
Run
npm run generate-env
or your normalionic serve
or evenionic build
and be sure to add the flag referring to the name of your js or json file as--env production
or--env prod
or--env p
-
Check your
src/providers/app-config
file to make sure it worked and for how call your variables.
ionic build <platform> --env p
will get an error saying that p is not a valid platform. To fix this, run the command like this:ionic build android -- --env p
for more information on what is actually going on, you can refer to the cordova cli docs found here specifically the the part related to[-- <platformOpts>]
.
- Add your config files to a .gitignore file to match all .json and .js
env/*.js
,env/*.json
andsrc/providers/app-config.ts
be sure not to include a reference that could target your app-config.ts.
My env folder has 3 files and their contents include:
- development.json
{
"apiUrl": "www.your-dev-url.com"
}
- production.js
var data = require(__dirname + "/production.json");
data.someApiKey = process.env.someKey;
module.exports = data;
- production.json
{
"apiUrl": "www.your-prod-site.com"
}
- if I run
npm run generate-env --env d
my component contains this:
...
@Injectable()
export class AppConfig {
constructor() {}
static get apiUrl() {
return "www.your-dev-url.com";
}
}
- if I run
npm run generate-env --env p
my component contains this:
...
@Injectable()
export class AppConfig {
constructor() {}
static get apiUrl() {
return "www.your-prod-site.com";
}
static get someApiKey() {
return undefined;
}
}
- GitHub Environment Proposal: ionic-team/ionic-app-scripts#762
- Base Architecture Design: It was posted by juarezpaf in the above mentioned thread on March 8th, 2017.