-
Notifications
You must be signed in to change notification settings - Fork 421
Expand file tree
/
Copy pathionic.mdc
More file actions
385 lines (297 loc) · 9.94 KB
/
ionic.mdc
File metadata and controls
385 lines (297 loc) · 9.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
---
description: This guide provides definitive best practices for developing high-performance, maintainable, and accessible Ionic applications using modern TypeScript and web standards.
globs: **/*.{js,jsx,ts,tsx}
---
# ionic Best Practices
Ionic Framework enables powerful cross-platform applications. Adhering to these guidelines ensures your codebase is robust, performant, and aligned with modern web development standards.
## 1. Code Organization and Structure
Adopt a consistent, component-centric file structure for clarity and maintainability.
### 1.1 One Component Per Directory
Each Ionic component (or Stencil component it wraps) must reside in its own directory, co-locating all related files.
❌ **BAD: Scattered files**
```
// components/my-button.tsx
// components/my-button.css
// components/my-card.tsx
// components/my-card.css
```
✅ **GOOD: Component-per-directory**
```
├── components
│ ├── ion-button
│ │ ├── ion-button.css
│ │ └── ion-button.tsx
│ └── ion-card
│ ├── ion-card.css
│ └── ion-card.tsx
```
### 1.2 Naming Conventions
Use descriptive, noun-based names for components, prefixed for uniqueness.
* **HTML Tag**: Use a unique, brand-specific prefix (e.g., `ion-`). Names should be nouns.
* **TS Class**: No prefix for the ES6 class name, as classes are scoped.
❌ **BAD: Verb-based or un-prefixed tags**
```tsx
// my-animating.tsx
@Component({ tag: 'animating-component' })
export class AnimatingComponent {}
```
✅ **GOOD: Noun-based, prefixed tags**
```tsx
// ion-animation.tsx
@Component({ tag: 'ion-animation' })
export class Animation {}
```
### 1.3 Component File Structure (Newspaper Metaphor)
Organize component class members logically, from high-level summaries to detailed implementations.
```typescript
@Component({
tag: 'ion-example',
styleUrls: {
ios: 'ion-example.ios.css',
md: 'ion-example.md.css',
},
})
export class IonExample {
/** 1. Internal Properties (not exposed) */
private internalValue: number = 0;
/** 2. Reference to host HTML element */
@Element() el!: HTMLElement;
/** 3. State() variables (internal reactive state) */
@State() isActive: boolean = false;
/** 4. Public Property API (@Prop()) with JSDocs */
/**
* The text to display on the button.
*/
@Prop() text: string = '';
/**
* If `true`, the button is disabled.
*/
@Prop() disabled: boolean = false;
/** 5. Prop lifecycle events (@Watch()) */
@Watch('disabled')
disabledChanged(newValue: boolean, oldValue: boolean) {
console.log(`Disabled changed from ${oldValue} to ${newValue}`);
}
/** 6. Events section (@Event()) with JSDocs */
/**
* Emitted when the button is clicked.
*/
@Event() ionClick!: EventEmitter<void>;
/** 7. Component lifecycle events (ordered by natural call order) */
connectedCallback() { /* ... */ }
disconnectedCallback() { /* ... */ }
componentWillLoad() { /* ... */ }
componentDidLoad() { /* ... */ }
componentWillRender() { /* ... */ }
componentDidRender() { /* ... */ }
/** 8. Listeners (@Listen()) */
@Listen('click', { target: 'document' })
onClick(event: Event) {
if (event.target === this.el) {
this.ionClick.emit();
}
}
/** 9. Public Methods (@Method()) with JSDocs */
/**
* Focuses the button.
*/
@Method()
async setFocus() {
this.el.focus();
}
/** 10. Private Methods (internal logic) */
private updateInternalState() {
this.internalValue++;
}
/** 11. Render function (JSX/TSX) */
render() {
return (
<button disabled={this.disabled} onClick={() => this.ionClick.emit()}>
{this.text}
</button>
);
}
}
```
## 2. TypeScript Best Practices
Leverage TypeScript for type safety, improved tooling, and maintainability.
### 2.1 Enforce Strict Typing
Always enable `noImplicitAny` and `strictNullChecks` in your `tsconfig.json`. Avoid `any` unless absolutely necessary.
❌ **BAD: Implicit `any`**
```typescript
function processData(data) { // data is implicitly 'any'
console.log(data.value);
}
```
✅ **GOOD: Explicit typing**
```typescript
interface Data {
value: string;
}
function processData(data: Data): void {
console.log(data.value);
}
```
### 2.2 Use `private` for Internal Members
Mark internal class properties and methods as `private` to enforce encapsulation and aid dead code detection.
❌ **BAD: All public by default**
```typescript
export class MyComponent {
helperMethod() { /* ... */ } // Public, but only used internally
}
```
✅ **GOOD: Encapsulated internals**
```typescript
export class MyComponent {
private helperMethod() { /* ... */ } // Clearly internal
}
```
### 2.3 JSDocs for Public API
Document all `@Prop()`, `@Event()`, and `@Method()` decorators with JSDoc comments to generate documentation and improve editor experience.
❌ **BAD: Undocumented public API**
```typescript
@Prop() value: string;
@Event() ionChange: EventEmitter<string>;
```
✅ **GOOD: Documented public API**
```typescript
/**
* The current value of the input.
*/
@Prop() value: string = '';
/**
* Emitted when the value changes.
*/
@Event() ionChange!: EventEmitter<string>;
```
## 3. Common Patterns and Anti-patterns
Adopt patterns that leverage Ionic's strengths and avoid common pitfalls.
### 3.1 Always `await` Asynchronous Native Plugin Calls
Capacitor/Cordova plugin calls are asynchronous. Always `await` their resolution to prevent race conditions and unexpected behavior.
❌ **BAD: Fire-and-forget native calls**
```typescript
import { Camera } from '@capacitor/camera';
async takePhoto() {
Camera.getPhoto({ /* ... */ }); // Missing await
console.log('Photo request sent'); // May log before photo is taken
}
```
✅ **GOOD: Await native calls**
```typescript
import { Camera, CameraResultType } from '@capacitor/camera';
async takePhoto() {
const photo = await Camera.getPhoto({
quality: 90,
allowEditing: false,
resultType: CameraResultType.Uri
});
console.log('Photo taken:', photo.webPath);
}
```
### 3.2 Prefer Ionic Components for UI
Leverage Ionic's rich set of UI components for adaptive styling, performance, and accessibility. Avoid custom implementations where an Ionic component exists.
❌ **BAD: Custom button for navigation**
```html
<button onclick="navigateTo('/home')">Home</button>
```
✅ **GOOD: Ionic button with router link**
```html
<ion-button routerLink="/home" routerDirection="forward">Home</ion-button>
```
### 3.3 Theming with CSS Variables
Customize your app's look and feel using Ionic's CSS Variables for consistent, platform-adaptive theming.
❌ **BAD: Hardcoded styles**
```css
.my-component {
background-color: #3880ff; /* Primary blue */
}
```
✅ **GOOD: CSS Variables for theming**
```css
.my-component {
background-color: var(--ion-color-primary);
}
```
## 4. Performance Considerations
Ionic is built for performance. Follow these to maintain a fast, responsive app.
### 4.1 Optimize DOM Updates
Avoid direct, heavy DOM manipulation. Let the framework (Angular, React, Vue, Stencil) manage DOM updates efficiently.
❌ **BAD: Manually updating styles on scroll**
```typescript
// In a scroll event listener
this.el.style.transform = `translateY(${scrollTop}px)`; // Triggers layout thrashing
```
✅ **GOOD: Use CSS transforms or Ionic's built-in scroll events**
```typescript
// Use CSS for animations or leverage Ionic's virtual scroll
// Or, if absolutely necessary, batch DOM reads/writes
```
### 4.2 Leverage Built-in Optimizations
Ionic components often include hardware-accelerated transitions, lazy loading, and tree-shaking. Ensure your build process enables these.
* **Tree-shaking**: Use modern bundlers (Webpack, Rollup) and ES Modules.
* **Lazy Loading**: For routes and components, especially in Angular/React/Vue.
## 5. Common Pitfalls and Gotchas
Be aware of these common issues to prevent bugs and performance regressions.
### 5.1 Ignoring Accessibility (a11y)
Ionic components are built with accessibility in mind, but developers must use them correctly. Run automated accessibility audits as part of CI.
❌ **BAD: Missing `aria-label` or semantic elements**
```html
<ion-icon name="menu" (click)="openMenu()"></ion-icon>
```
✅ **GOOD: Accessible elements**
```html
<ion-menu-button auto-hide="false"></ion-menu-button>
<!-- Or for a standalone icon that triggers an action -->
<ion-icon name="menu" aria-label="Open menu" (click)="openMenu()"></ion-icon>
```
### 5.2 Using Deprecated TSLint Configurations
TSLint is deprecated. Migrate to ESLint with `@stencil-community/eslint-plugin` and `eslint-config-ionic` for modern static analysis.
❌ **BAD: Relying on `tslint.json`**
```json
// tslint.json
{
"extends": "tslint-ionic-rules/strict"
}
```
✅ **GOOD: Using ESLint**
```json
// .eslintrc.js
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@stencil-community/recommended',
'@ionic/eslint-config/recommended'
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', '@stencil-community'],
// ... other rules and configs
};
```
## 6. Testing Approaches
Implement a robust testing strategy for reliability and maintainability.
### 6.1 Unit Testing
Use Jest for unit testing individual components, services, and utilities. Focus on isolated logic.
```typescript
// my-service.spec.ts
import { MyService } from './my-service';
describe('MyService', () => {
let service: MyService;
beforeEach(() => {
service = new MyService();
});
it('should return the correct value', () => {
expect(service.calculate(2, 3)).toBe(5);
});
});
```
### 6.2 End-to-End (E2E) Testing
Use Playwright or Cypress for E2E tests to simulate user interactions across your application.
```javascript
// e2e/home.spec.ts (example with Playwright)
import { test, expect } from '@playwright/test';
test('should navigate to home and display title', async ({ page }) => {
await page.goto('/home');
await expect(page.locator('ion-title')).toHaveText('Home');
});
```