Environment specific arguments in Ionic 3
Based on the tutorial of Rob Ferguson there are three things to do. Depending on your file structure which is completely interchangeable (./
marks the root directory of your application).
./tsconfig.json
{
"compilerOptions": {
"baseUrl": "./src",
"paths": {
"@env": [ "env/env" ]
},
...
}
...
}
./package.json
{
"config": {
"ionic_source_map_type": "source-map",
"ionic_webpack": "./config/webpack.config.js"
},
...
}
./config/webpack.config.js (depending on ionic_webpack
in your package.json
)
/*
* The webpack config exports an object that has a valid webpack configuration
* For each environment name. By default, there are two Ionic environments:
* "dev" and "prod". As such, the webpack.config.js exports a dictionary object
* with "keys" for "dev" and "prod", where the value is a valid webpack configuration
* For details on configuring webpack, see their documentation here
* https://webpack.js.org/configuration/
*/
const path = require('path');
// If you start your building process with the flag --prod this will equal "prod" otherwise "dev"
const ENV = process.env.IONIC_ENV;
const devConfig = {
entry: ...,
output: {...},
devtool: ...,
resolve: {
extensions: [...],
modules: [...],
alias: {
// this distincts your specific environment "dev" and "prod"
"@env": path.resolve(`./src/env/env.ts`),
}
},
module: {...},
plugins: [...],
node: {...}
};
const prodConfig = {
entry: ...,
output: {...},
devtool: ...,
resolve: {
extensions: [...],
modules: [...],
alias: {
// this distincts your specific environment "dev" and "prod"
"@env": path.resolve(`./src/env/env.prod.ts`),
}
},
module: {...},
plugins: [...],
node: {...}
};
module.exports = {
dev: devConfig,
prod: prodConfig
}
Explanation
The magic comes in with devConfig.resolve.alias
and prodConfig.resolve.alias
. This line of code creates an importable alias like your own modules or node modules. Now it will be possible to inject through import { ENV } from '@env'
to any module, component, service, pipe or what ever you like.
Note
Do not forget to create your environment specific files. In this example you will need a file structure like that one:
./
| package.json
│ tsconfig.json
│
└── config
│ webpack.config.js
│
└── src
│
└── env
env.ts (dev environment variables)
env.prod.ts (prod environment variables)
Example file
./src/env/env.ts (by default it will be development)
export const ENV = {
production: false,
isDebugMode: true
};
./src/env/env.prod.ts
export const ENV = {
production: true,
isDebugMode: false
};