javascript – Ionic 3中的环境特定参数

前端之家收集整理的这篇文章主要介绍了javascript – Ionic 3中的环境特定参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以何种方式使用离子命令行界面的环境特定参数,如离子构建 android –prod –device,根据环境对 javascript / typescript代码进行区分,例如:生产和发展?

我应该使用process.env.IONIC_ENV吗?或者我可以通过哪种方式查询这种区别?

解决方法

根据 Rob Ferguson的教程,有三件事要做.根据您的文件结构完全可以互换(./标记应用程序的根目录).

./tsconfig.json

  1. {
  2. "compilerOptions": {
  3. "baseUrl": "./src","paths": {
  4. "@env": [ "env/env" ]
  5. },...
  6. }
  7. ...
  8. }

./package.json

  1. {
  2. "config": {
  3. "ionic_source_map_type": "source-map","ionic_webpack": "./config/webpack.config.js"
  4. },...
  5. }

./config/webpack.config.js(取决于package.json中的ionic_webpack)

  1. /*
  2. * The webpack config exports an object that has a valid webpack configuration
  3. * For each environment name. By default,there are two Ionic environments:
  4. * "dev" and "prod". As such,the webpack.config.js exports a dictionary object
  5. * with "keys" for "dev" and "prod",where the value is a valid webpack configuration
  6. * For details on configuring webpack,see their documentation here
  7. * https://webpack.js.org/configuration/
  8. */
  9.  
  10. const path = require('path');
  11. // If you start your building process with the flag --prod this will equal "prod" otherwise "dev"
  12. const ENV = process.env.IONIC_ENV;
  13.  
  14. const devConfig = {
  15. entry: ...,output: {...},devtool: ...,resolve: {
  16. extensions: [...],modules: [...],alias: {
  17. // this distincts your specific environment "dev" and "prod"
  18. "@env": path.resolve(`./src/env/env.ts`),}
  19. },module: {...},plugins: [...],node: {...}
  20. };
  21.  
  22. const prodConfig = {
  23. entry: ...,alias: {
  24. // this distincts your specific environment "dev" and "prod"
  25. "@env": path.resolve(`./src/env/env.prod.ts`),node: {...}
  26. };
  27.  
  28. module.exports = {
  29. dev: devConfig,prod: prodConfig
  30. }

说明

魔法来自devConfig.resolve.alias和prodConfig.resolve.alias.这行代码创建了一个可导入的别名,如您自己的模块或节点模块.现在可以通过导入{ENV}从’@env’注入任何模块,组件,服务,管道或任何你喜欢的东西.

注意

不要忘记创建特定于环境的文件.在这个例子中,你需要一个像这样的文件结构:

  1. ./
  2. | package.json
  3. tsconfig.json
  4. └── config
  5. webpack.config.js
  6. └── src
  7. └── env
  8. env.ts (dev environment variables)
  9. env.prod.ts (prod environment variables)

示例文件

./src/env/env.ts(默认情况下是开发)

  1. export const ENV = {
  2. production: false,isDebugMode: true
  3. };

./src/env/env.prod.ts

  1. export const ENV = {
  2. production: true,isDebugMode: false
  3. };

猜你在找的JavaScript相关文章