0
# Warning System
1
2
Consistent warning and debugging message display system for development and production environments.
3
4
## Capabilities
5
6
### Basic Warning
7
8
Display warning messages with consistent formatting.
9
10
```typescript { .api }
11
/**
12
* Display a warning message with intlify prefix
13
* @param msg - Warning message to display
14
* @param err - Optional error object to display stack trace
15
*/
16
function warn(msg: string, err?: Error): void;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
import { warn } from "@intlify/shared";
23
24
// Basic warning message
25
warn("Translation key not found");
26
27
// Warning with error details
28
try {
29
riskyOperation();
30
} catch (error) {
31
warn("Operation failed", error);
32
}
33
34
// Conditional warnings
35
function validateInput(input: any) {
36
if (!input) {
37
warn("Input validation failed: empty input provided");
38
return false;
39
}
40
return true;
41
}
42
```
43
44
### Warning Once
45
46
Display warning messages only once per unique message to avoid spam.
47
48
```typescript { .api }
49
/**
50
* Display a warning message only once per unique message
51
* @param msg - Warning message to display once
52
*/
53
function warnOnce(msg: string): void;
54
```
55
56
**Usage Examples:**
57
58
```typescript
59
import { warnOnce } from "@intlify/shared";
60
61
// This warning will only appear once, even if called multiple times
62
function deprecatedFunction() {
63
warnOnce("deprecatedFunction is deprecated, use newFunction instead");
64
// Function implementation...
65
}
66
67
// Called multiple times, but warning shows only once
68
deprecatedFunction(); // Warning appears
69
deprecatedFunction(); // No warning
70
deprecatedFunction(); // No warning
71
72
// Different messages are tracked separately
73
function anotherDeprecatedFunction() {
74
warnOnce("anotherDeprecatedFunction is deprecated");
75
// This will show because it's a different message
76
}
77
```
78
79
## Warning System Behavior
80
81
### Console Output Format
82
83
All warnings are prefixed with `[intlify]` for consistent identification:
84
85
```
86
[intlify] Translation key not found
87
[intlify] Operation failed
88
Error: Something went wrong
89
at Object.<anonymous> (/path/to/file.js:10:15)
90
...
91
```
92
93
### Environment Detection
94
95
The warning system automatically detects if `console` is available:
96
- **Browser environments**: Uses `console.warn()`
97
- **Node.js environments**: Uses `console.warn()`
98
- **Environments without console**: Silent (no errors thrown)
99
100
### Error Stack Traces
101
102
When an `Error` object is provided to `warn()`, the stack trace is displayed using `console.warn(err.stack)`.
103
104
## Advanced Usage Patterns
105
106
### Conditional Warnings
107
108
```typescript
109
import { warn, warnOnce } from "@intlify/shared";
110
111
// Development-only warnings
112
const isDevelopment = process.env.NODE_ENV === 'development';
113
114
function devWarn(message: string) {
115
if (isDevelopment) {
116
warn(message);
117
}
118
}
119
120
// Usage
121
devWarn("This warning only appears in development");
122
```
123
124
### Warning Categories
125
126
```typescript
127
import { warn } from "@intlify/shared";
128
129
// Create category-specific warning functions
130
function createCategoryWarner(category: string) {
131
return (message: string, error?: Error) => {
132
warn(`[${category}] ${message}`, error);
133
};
134
}
135
136
const i18nWarn = createCategoryWarner("i18n");
137
const routerWarn = createCategoryWarner("router");
138
139
// Usage
140
i18nWarn("Missing translation for key: user.name");
141
routerWarn("Route not found: /invalid-path");
142
143
// Output:
144
// [intlify] [i18n] Missing translation for key: user.name
145
// [intlify] [router] Route not found: /invalid-path
146
```
147
148
### Performance-Conscious Warnings
149
150
```typescript
151
import { warnOnce } from "@intlify/shared";
152
153
class PerformanceMonitor {
154
private warningThresholds = {
155
slow: 100,
156
verySlow: 1000
157
};
158
159
measureOperation(name: string, operation: () => void) {
160
const start = Date.now();
161
operation();
162
const duration = Date.now() - start;
163
164
if (duration > this.warningThresholds.verySlow) {
165
warnOnce(`Operation "${name}" is very slow (${duration}ms)`);
166
} else if (duration > this.warningThresholds.slow) {
167
warnOnce(`Operation "${name}" is slow (${duration}ms)`);
168
}
169
}
170
}
171
```
172
173
### Error Context Enhancement
174
175
```typescript
176
import { warn } from "@intlify/shared";
177
178
function enhancedWarn(message: string, context?: Record<string, any>, error?: Error) {
179
let fullMessage = message;
180
181
if (context) {
182
const contextStr = Object.entries(context)
183
.map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
184
.join(", ");
185
fullMessage += ` (Context: ${contextStr})`;
186
}
187
188
warn(fullMessage, error);
189
}
190
191
// Usage
192
enhancedWarn("API request failed", {
193
url: "/api/users",
194
method: "GET",
195
status: 404
196
});
197
198
// Output: [intlify] API request failed (Context: url: "/api/users", method: "GET", status: 404)
199
```
200
201
## Integration with Intlify Ecosystem
202
203
### Translation Warnings
204
205
```typescript
206
import { warn, warnOnce } from "@intlify/shared";
207
208
function handleTranslationIssues() {
209
// One-time warnings for missing configurations
210
warnOnce("Fallback locale not configured");
211
212
// Per-occurrence warnings for runtime issues
213
warn("Translation key 'user.welcome' not found in locale 'fr'");
214
}
215
```
216
217
### Development vs Production
218
219
```typescript
220
import { warn, warnOnce } from "@intlify/shared";
221
222
// The warning system works in both development and production
223
// Use conditional logic for development-only warnings
224
function createI18nInstance(options: any) {
225
if (process.env.NODE_ENV === 'development') {
226
if (!options.locale) {
227
warn("No default locale specified, using 'en'");
228
}
229
230
if (options.legacy === undefined) {
231
warnOnce("Consider setting legacy mode explicitly for better performance");
232
}
233
}
234
235
// Production warnings for critical issues
236
if (!options.messages) {
237
warn("No translation messages provided");
238
}
239
}
240
```
241
242
## Memory Management
243
244
The `warnOnce` function maintains an internal record of displayed messages:
245
246
- **Memory usage**: Grows with unique warning messages
247
- **Cleanup**: No automatic cleanup (messages persist for application lifetime)
248
- **Best practice**: Use `warnOnce` for finite set of deprecation warnings, not dynamic content
249
250
```typescript
251
// ✅ Good: Finite set of deprecation warnings
252
warnOnce("Method X is deprecated, use Y instead");
253
254
// ❌ Avoid: Dynamic content that could cause memory leaks
255
warnOnce(`User ${userId} has invalid data`); // Could create many unique messages
256
```