nativescript — правило для Cursor: что делает и как установить
Правило задаёт практики для NativeScript-приложений на TypeScript, Vue и других поддержанных стеках. Пригодится для мобильного UI и нативного кода.
.cursor/rules/nativescript.mdcЧто делает nativescript
Правило задаёт структуру NativeScript-кода: модульные компоненты и сервисы, отдельные файлы .ios.ts и .android.ts для платформенной логики, а также папку custom-native с общими типами и реализациями. Имена переменных для платформ получают префиксы ios или android.
Для UI оно требует TailwindCSS с @nativescript/tailwind и tailwindcss, предлагает GridLayout для сложных экранов и StackLayout для линейных блоков. Также правило охватывает @NativeClass(), делегаты iOS, условный код через __ANDROID__ и __APPLE__, очистку таймеров и работу со состоянием во фреймворках.
После изменений в App_Resources или package.json правило советует запускать ns clean. Если проект использует другой CSS-фреймворк, требование TailwindCSS станет конфликтующим ограничением.
Какие задачи решает
- организовать платформенный код NativeScript
- разделить iOS- и Android-реализации
- настроить стили NativeScript через TailwindCSS
- предотвратить утечки из-за таймеров
- собрать адаптивный экран на
GridLayout
Примеры запросов агенту
- Организуй этот экран NativeScript через
GridLayoutи вынеси платформенный код в отдельные файлы. - Проверь компонент Vue на соответствие правилам NativeScript и замени глубокую вложенность layout-контейнеров.
- Добавь делегат iOS для этого нативного класса и сохрани его экземпляр в области видимости класса.
Как установить nativescript
Вручную: положить файлы
.cursor/rules/nativescript.mdcВо frontmatter: description, globs, alwaysApply
Вручную: положить файлы
.claude/rules/nativescript.mdПоле paths во frontmatter ограничивает файлы: globs из источника → paths
AGENTS.md
Codex читает AGENTS.md: вставьте текст правила туда
Вручную: положить файлы
.github/instructions/nativescript.instructions.mdПоле applyTo задаёт, к каким файлам применять: globs из источника → applyTo
Вручную: положить файлы
.devin/rules/nativescript.mdВручную: положить файлы
.clinerules/nativescript.mdПо шагам, с командами для каждой платформы: Cursor rules: файлы .mdc, четыре режима и замена .cursorrules
Вопросы о nativescript
Как установить nativescript в Cursor?
Добавьте правило в файл .cursor/rules/nativescript.mdc.
Что делает правило nativescript?
Оно задаёт практики для структуры NativeScript-кода, платформенных файлов, TailwindCSS, layout-контейнеров, делегатов iOS и управления таймерами.
Какие файлы обрабатывает nativescript?
Правило нацелено на файлы .tsx, .ts, .vue и .svelte, включая пути src/**/*.ts, app/**/*.ts, src/**/*.tsx, app/**/*.tsx, src/**/*.vue, app/**/*.vue, src/**/*.svelte.
Исходный текст
nativescript.mdc · CC0-1.0
---
description: "NativeScript best practices and patterns for mobile applications"
globs: **/*.tsx, **/*.ts, **/*.vue, **/*.svelte, src/**/*.ts, app/**/*.ts, src/**/*.tsx, app/**/*.tsx, src/**/*.vue, app/**/*.vue, src/**/*.svelte
alwaysApply: false
---
# NativeScript Best Practices
## Code Style and Structure
- Organize code using modular components and services for maintainability.
- Use platform-specific files (`.ios.ts`, `.android.ts`) when code exceeds 20 platform-specific lines.
- When creating custom native code, use a folder structure like `custom-native/index.ios.ts`, `custom-native/index.android.ts`, `custom-native/common.ts`, `custom-native/index.d.ts` to keep platform-specific code organized and easy to import with single import elsewhere, replacing `custom-native` with the name of the custom code.
## Naming Conventions
- Prefix platform-specific variables with `ios` or `android` (e.g., `iosButtonStyle`).
- Name custom components and styles descriptively (`primaryButtonStyle`, `userProfileView`).
## Usage
- Use `@NativeClass()` when extending native classes when needed
- For iOS, when extending native classes, always use `static ObjCProtocols = [AnyUIKitDelegate];` to declare custom delegates if a delegate is required or used.
- For iOS, always retain custom delegate instances to prevent garbage collection. For example, `let delegate = MyCustomDelegate.new() as MyCustomDelegate`, and ensure it is retained in the class scope.
- Favor `__ANDROID__` and `__APPLE__` for conditional platform code with tree-shaking.
- Track and clean up all timers (`setTimeout`, `setInterval`) to avoid memory leaks.
## UI and Styling
- Always TailwindCSS as the CSS Framework using `"@nativescript/tailwind": "^2.1.0"` for consistent styling paired with `"tailwindcss": "~3.4.0"`.
- Add ios: and android: style variants for platform-specific styling, addVariant('android', '.ns-android &'), addVariant('ios', '.ns-ios &');
- darkMode: ['class', '.ns-dark']
- Leverage `GridLayout` or `StackLayout` for flexible, responsive layouts. Place more emphasis on proper GridLayout usage for complex layouts but use StackLayout for simpler, linear arrangements.
- Use `visibility: 'hidden'` for elements that should not affect layout when hidden.
## Performance Optimization
- Try to avoid deeply nesting layout containers but instead use `GridLayout` wisely to setup complex layouts.
- Avoid direct manipulation of the visual tree during runtime to minimize rendering overhead.
- Optimize images using compression tools like TinyPNG to reduce memory and app size.
- Clean the project (`ns clean`) after modifying files in `App_Resources` or `package.json`.
## Key Conventions
- Reuse components and styles to avoid duplication.
- Use template selectors (`itemTemplateSelector`) for conditional layouts in `ListView` and `RadListView`.
- Minimize heavy computations in UI bindings or methods.
- Only if using plain xml bindings, use `Observable` or `ObservableArray` properties to reflect state changes efficiently.
- When using Angular, React, Solid, Svelte or Vue, always leverage their respective state management, lifecycle hooks, rendering optimizations and reactive bindings for optimal performance.
© PatrickJS · CC0-1.0 · PatrickJS/awesome-cursorrules