Variabili d'Ambiente
Guida alla configurazione delle variabili d'ambiente per Tess UI Library.
Overview
La libreria supporta configurazione tramite variabili d'ambiente sia in build-time che runtime, permettendo deployment configurabili senza rebuild.
Build-Time Configuration
Environment Files
Crea file environment per ogni target di deployment:
// src/environments/environment.ts (development)
export const environment = {
production: false,
apiUrl: 'http://localhost:3000/api',
appInsightsConnectionString: '',
logLevel: 'debug',
enableTracing: true,
};
// src/environments/environment.staging.ts
export const environment = {
production: false,
apiUrl: 'https://api.staging.example.com',
appInsightsConnectionString: 'InstrumentationKey=xxx-staging',
logLevel: 'info',
enableTracing: true,
};
// src/environments/environment.prod.ts
export const environment = {
production: true,
apiUrl: 'https://api.example.com',
appInsightsConnectionString: 'InstrumentationKey=xxx-prod',
logLevel: 'warn',
enableTracing: false,
};
Angular Configuration
// angular.json
{
"projects": {
"your-app": {
"architect": {
"build": {
"configurations": {
"development": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.ts"
}
]
},
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
},
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
}
}
}
}
}
Build Commands
// package.json
{
"scripts": {
"build": "ng build",
"build:staging": "ng build --configuration=staging",
"build:prod": "ng build --configuration=production"
}
}
Runtime Configuration
Per Docker e deployment cloud, usa configurazione runtime.
Config Service
// config.service.ts
import { Injectable } from '@angular/core';
export interface AppConfig {
apiUrl: string;
appInsightsConnectionString: string;
logLevel: 'debug' | 'info' | 'warn' | 'error';
enableTracing: boolean;
uiKit: 'primeng' | 'bootstrap' | 'material';
}
@Injectable({ providedIn: 'root' })
export class ConfigService {
private config: AppConfig = {
apiUrl: '',
appInsightsConnectionString: '',
logLevel: 'info',
enableTracing: true,
uiKit: 'primeng',
};
loadConfig(): Promise<void> {
return fetch('/assets/config.json')
.then(response => response.json())
.then(config => {
this.config = { ...this.config, ...config };
})
.catch(error => {
console.error('Errore caricamento configurazione:', error);
// Usa valori di default
});
}
get<K extends keyof AppConfig>(key: K): AppConfig[K] {
return this.config[key];
}
getAll(): AppConfig {
return { ...this.config };
}
}
APP_INITIALIZER
// app.config.ts
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { ConfigService } from './services/config.service';
export function initializeApp(configService: ConfigService): () => Promise<void> {
return () => configService.loadConfig();
}
export const appConfig: ApplicationConfig = {
providers: [
{
provide: APP_INITIALIZER,
useFactory: initializeApp,
deps: [ConfigService],
multi: true,
},
],
};
Config JSON Generation
#!/bin/bash
# generate-config.sh
cat > ./dist/your-app/assets/config.json << EOF
{
"apiUrl": "${API_URL}",
"appInsightsConnectionString": "${APP_INSIGHTS_CONNECTION_STRING}",
"logLevel": "${LOG_LEVEL:-info}",
"enableTracing": ${ENABLE_TRACING:-true},
"uiKit": "${UI_KIT:-primeng}"
}
EOF
Docker Integration
# Dockerfile
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build -- --configuration=production
FROM nginx:alpine
COPY --from=build /app/dist/your-app /usr/share/nginx/html
COPY docker/nginx.conf /etc/nginx/nginx.conf
# Script per generare config.json
COPY docker/generate-config.sh /docker-entrypoint.d/01-generate-config.sh
RUN chmod +x /docker-entrypoint.d/01-generate-config.sh
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
#!/bin/sh
# docker/generate-config.sh
cat > /usr/share/nginx/html/assets/config.json << EOF
{
"apiUrl": "${API_URL}",
"appInsightsConnectionString": "${APP_INSIGHTS_CONNECTION_STRING}",
"logLevel": "${LOG_LEVEL:-info}",
"enableTracing": ${ENABLE_TRACING:-true},
"uiKit": "${UI_KIT:-primeng}"
}
EOF
Docker Compose
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "80:80"
environment:
- API_URL=https://api.example.com
- APP_INSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx
- LOG_LEVEL=info
- ENABLE_TRACING=true
- UI_KIT=primeng
Variabili d'Ambiente Supportate
Core
| Variabile | Tipo | Default | Descrizione |
|---|---|---|---|
API_URL | string | - | URL base per le API |
LOG_LEVEL | string | 'info' | Livello di logging (debug, info, warn, error) |
ENABLE_TRACING | boolean | true | Abilita traceability service |
UI_KIT | string | 'primeng' | UI Kit da utilizzare |
Logging
| Variabile | Tipo | Default | Descrizione |
|---|---|---|---|
APP_INSIGHTS_CONNECTION_STRING | string | - | Connection string per Application Insights |
ENABLE_CONSOLE_LOGGING | boolean | true | Abilita logging su console |
ENABLE_AUTO_ROUTE_TRACKING | boolean | true | Tracking automatico navigazione |
Storage
| Variabile | Tipo | Default | Descrizione |
|---|---|---|---|
STORAGE_NAMESPACE | string | 'tess' | Namespace per localStorage |
TRACE_ID_STORAGE_KEY | string | 'traceId' | Chiave storage per TraceId |
Theme
| Variabile | Tipo | Default | Descrizione |
|---|---|---|---|
DEFAULT_THEME | string | 'light' | Tema di default |
AVAILABLE_THEMES | string | 'light,dark' | Temi disponibili (separati da virgola) |
Best Practices
1. Non committare segreti
# .gitignore
src/environments/environment.*.local.ts
.env
.env.local
config.json
2. Usa .env.example
# .env.example
API_URL=https://api.example.com
APP_INSIGHTS_CONNECTION_STRING=InstrumentationKey=xxx
LOG_LEVEL=info
ENABLE_TRACING=true
UI_KIT=primeng
3. Validazione Config
// config.service.ts
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class ConfigService {
loadConfig(): Promise<void> {
return fetch('/assets/config.json')
.then(response => response.json())
.then(config => {
this.validateConfig(config);
this.config = { ...this.config, ...config };
});
}
private validateConfig(config: Partial<AppConfig>): void {
if (!config.apiUrl) {
throw new Error('API_URL è obbligatorio');
}
if (!/^https?:\/\//.test(config.apiUrl)) {
throw new Error('API_URL deve essere un URL valido');
}
const validLogLevels = ['debug', 'info', 'warn', 'error'];
if (config.logLevel && !validLogLevels.includes(config.logLevel)) {
throw new Error(\`LOG_LEVEL deve essere uno di: \${validLogLevels.join(', ')}\`);
}
}
}
4. Type Safety
// config.types.ts
export interface AppConfig {
apiUrl: string;
appInsightsConnectionString: string;
logLevel: LogLevel;
enableTracing: boolean;
uiKit: UiKit;
}
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
export type UiKit = 'primeng' | 'bootstrap' | 'material';
// config.schema.ts
import Ajv, { JSONSchemaType } from 'ajv';
const schema: JSONSchemaType<AppConfig> = {
type: 'object',
properties: {
apiUrl: { type: 'string', pattern: '^https?://' },
appInsightsConnectionString: { type: 'string' },
logLevel: { type: 'string', enum: ['debug', 'info', 'warn', 'error'] },
enableTracing: { type: 'boolean' },
uiKit: { type: 'string', enum: ['primeng', 'bootstrap', 'material'] },
},
required: ['apiUrl'],
};
export function validateConfig(config: unknown): AppConfig {
const ajv = new Ajv();
const validate = ajv.compile(schema);
if (!validate(config)) {
throw new Error(\`Invalid config: \${JSON.stringify(validate.errors)}\`);
}
return config as AppConfig;
}
Kubernetes ConfigMap
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
config.json: |
{
"apiUrl": "https://api.production.com",
"appInsightsConnectionString": "InstrumentationKey=xxx",
"logLevel": "info",
"enableTracing": true,
"uiKit": "primeng"
}
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: app-deployment
spec:
template:
spec:
containers:
- name: app
image: your-app:latest
volumeMounts:
- name: config-volume
mountPath: /usr/share/nginx/html/assets
readOnly: true
volumes:
- name: config-volume
configMap:
name: app-config
Azure App Service
# Configura variabili in Azure Portal o CLI
az webapp config appsettings set \
--resource-group myResourceGroup \
--name myAppName \
--settings \
API_URL="https://api.production.com" \
APP_INSIGHTS_CONNECTION_STRING="InstrumentationKey=xxx" \
LOG_LEVEL="info"
AWS Elastic Beanstalk
# .ebextensions/environment.config
option_settings:
aws:elasticbeanstalk:application:environment:
API_URL: "https://api.production.com"
APP_INSIGHTS_CONNECTION_STRING: "InstrumentationKey=xxx"
LOG_LEVEL: "info"
ENABLE_TRACING: "true"