特定于环境的参数以何种方式与 ionic 命令行界面一起使用,例如 ionic build android --prod --device
以根据环境在 JavaScript/Typescript 代码中进行区分,例如生产和开发?
我应该使用 process.env.IONIC_ENV
吗?或者我可以通过什么方式查询这种区别?
最佳答案
基于Rob Ferguson的教程要做三件事。取决于完全可互换的文件结构(./
标记应用程序的根目录)。
./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 (取决于 package.json
中的 ionic_webpack
)
/*
* 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
}
解释
魔法来自 devConfig.resolve.alias
和 prodConfig.resolve.alias
。这行代码创建了一个可导入的别名,就像您自己的模块或节点模块一样。现在可以通过 import { ENV } from '@env'
注入(inject)任何模块、组件、服务、管道或任何你喜欢的东西。
注意事项
不要忘记创建您的环境特定文件。在此示例中,您将需要一个类似这样的文件结构:
./
| package.json
│ tsconfig.json
│
└── config
│ webpack.config.js
│
└── src
│
└── env
env.ts (dev environment variables)
env.prod.ts (prod environment variables)
示例文件
./src/env/env.ts (默认为开发)
export const ENV = {
production: false,
isDebugMode: true
};
./src/env/env.prod.ts
export const ENV = {
production: true,
isDebugMode: false
};
关于javascript - Ionic 3 中的环境特定参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695340/