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

以何种方式使用离子命令行界面的环境特定参数,如离子构建 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: ...,alias: {
      // this distincts your specific environment "dev" and "prod"
      "@env": path.resolve(`./src/env/env.prod.ts`),node: {...}
};

module.exports = {
  dev: devConfig,prod: prodConfig
}

说明

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

注意

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

./
|   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
};

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...