NativeScript 第一个应用 #

创建项目 #

使用 CLI 创建 #

bash
# 创建 Angular 项目
ns create my-app --ng

# 创建 Vue 项目
ns create my-app --vue

# 创建 React 项目
ns create my-app --react

# 创建纯 TypeScript 项目
ns create my-app --ts

项目模板选择 #

text
┌─────────────────────────────────────────────────────────────┐
│                    项目模板                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  --ng        Angular + NativeScript                         │
│              适合 Angular 开发者                             │
│              完整的 Angular 生态                             │
│                                                             │
│  --vue       Vue + NativeScript                             │
│              适合 Vue 开发者                                 │
│              Vue 3 支持                                      │
│                                                             │
│  --react     React + NativeScript                           │
│              适合 React 开发者                               │
│              React 18 支持                                   │
│                                                             │
│  --ts        纯 TypeScript                                   │
│              轻量级                                          │
│              最大灵活性                                      │
│                                                             │
└─────────────────────────────────────────────────────────────┘

创建过程 #

bash
$ ns create my-app --ng

? What framework would you like to use? Angular
? What template would you like to start from? Blank

✓ Creating project structure
✓ Installing dependencies
✓ Setting up configuration

Project my-app was created successfully!

项目结构 #

Angular 项目结构 #

text
my-app/
├── src/
│   ├── app/
│   │   ├── app.component.html    # 根组件模板
│   │   ├── app.component.ts      # 根组件逻辑
│   │   ├── app.css               # 全局样式
│   │   ├── app.module.ts         # 根模块
│   │   ├── app.routing.ts        # 路由配置
│   │   └── home/                 # 首页模块
│   │       ├── home.component.html
│   │       ├── home.component.ts
│   │       └── home.css
│   ├── assets/                   # 静态资源
│   ├── environments/             # 环境配置
│   ├── main.ts                   # 入口文件
│   └── styles.css                # 全局样式
├── angular.json                  # Angular 配置
├── package.json                  # 项目依赖
├── tsconfig.json                 # TypeScript 配置
└── nativescript.config.ts        # NativeScript 配置

Vue 项目结构 #

text
my-app/
├── app/
│   ├── App.vue                   # 根组件
│   ├── main.ts                   # 入口文件
│   ├── components/               # 组件目录
│   │   └── Home.vue
│   ├── screens/                  # 页面目录
│   │   └── Home.vue
│   └── router/                   # 路由配置
│       └── index.ts
├── assets/                       # 静态资源
├── App_Resources/                # 原生资源
│   ├── Android/
│   └── iOS/
├── package.json
├── tsconfig.json
└── nativescript.config.ts

纯 TypeScript 项目结构 #

text
my-app/
├── app/
│   ├── app.xml                   # 主页面 XML
│   ├── app.ts                    # 入口文件
│   ├── app.css                   # 样式文件
│   ├── main-page.xml             # 首页 XML
│   ├── main-page.ts              # 首页逻辑
│   └── main-page.css             # 首页样式
├── App_Resources/                # 原生资源
├── package.json
├── tsconfig.json
└── nativescript.config.ts

运行应用 #

运行在模拟器 #

bash
# 运行 Android 模拟器
ns run android

# 运行 iOS 模拟器(仅 macOS)
ns run ios

# 指定模拟器
ns run android --device <device-id>
ns run ios --device <device-id>

运行在真机 #

bash
# Android 真机(需开启 USB 调试)
ns run android --device

# iOS 真机(需配置签名)
ns run ios --device

运行选项 #

bash
# 启用热重载
ns run android --hmr

# 清理后运行
ns run android --clean

# 发布模式
ns run android --release

# 指定配置
ns run android --env.aot

Hello World 示例 #

纯 TypeScript 版本 #

main-page.xml - 界面布局

xml
<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo">
    <ActionBar title="My App" />
    
    <GridLayout>
        <StackLayout class="p-20">
            <Label text="Hello, NativeScript!" 
                   class="h1 text-center" 
                   textWrap="true" />
            
            <Button text="Tap me!" 
                    tap="onTap" 
                    class="btn btn-primary" />
            
            <Label text="{{ message }}" 
                   class="h2 text-center" 
                   textWrap="true" />
        </StackLayout>
    </GridLayout>
</Page>

main-page.ts - 页面逻辑

typescript
import { Observable } from '@nativescript/core';

export function onNavigatingTo(args) {
    const page = args.object;
    page.bindingContext = new HelloWorldModel();
}

export function onTap(args) {
    const page = args.object.page;
    const viewModel = page.bindingContext as HelloWorldModel;
    viewModel.onTap();
}

class HelloWorldModel extends Observable {
    private _message: string = 'Tap the button!';
    
    get message(): string {
        return this._message;
    }
    
    set message(value: string) {
        if (this._message !== value) {
            this._message = value;
            this.notifyPropertyChange('message', value);
        }
    }
    
    onTap() {
        this.message = 'Hello, NativeScript!';
    }
}

main-page.css - 样式

css
.h1 {
    font-size: 32;
    font-weight: bold;
}

.h2 {
    font-size: 24;
    color: #333;
}

.text-center {
    text-align: center;
}

.p-20 {
    padding: 20;
}

.btn {
    padding: 12 24;
    border-radius: 8;
    font-size: 16;
}

.btn-primary {
    background-color: #3498db;
    color: white;
}

Angular 版本 #

home.component.html

xml
<ActionBar title="My App">
    <ActionItem text="Menu" android.position="actionBar"></ActionItem>
</ActionBar>

<GridLayout>
    <StackLayout class="p-20">
        <Label text="Hello, NativeScript!" 
               class="h1 text-center" 
               textWrap="true"></Label>
        
        <Button text="Tap me!" 
                (tap)="onTap()" 
                class="btn btn-primary"></Button>
        
        <Label [text]="message" 
               class="h2 text-center" 
               textWrap="true"></Label>
    </StackLayout>
</GridLayout>

home.component.ts

typescript
import { Component } from '@angular/core';

@Component({
    selector: 'ns-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})
export class HomeComponent {
    message: string = 'Tap the button!';
    
    onTap() {
        this.message = 'Hello, NativeScript!';
    }
}

Vue 版本 #

Home.vue

vue
<template>
    <Page>
        <ActionBar title="My App" />
        
        <GridLayout>
            <StackLayout class="p-20">
                <Label text="Hello, NativeScript!" 
                       class="h1 text-center" 
                       textWrap="true" />
                
                <Button text="Tap me!" 
                        @tap="onTap" 
                        class="btn btn-primary" />
                
                <Label :text="message" 
                       class="h2 text-center" 
                       textWrap="true" />
            </StackLayout>
        </GridLayout>
    </Page>
</template>

<script>
export default {
    data() {
        return {
            message: 'Tap the button!'
        };
    },
    methods: {
        onTap() {
            this.message = 'Hello, NativeScript!';
        }
    }
};
</script>

<style scoped>
.h1 {
    font-size: 32;
    font-weight: bold;
}

.h2 {
    font-size: 24;
    color: #333;
}

.text-center {
    text-align: center;
}

.p-20 {
    padding: 20;
}

.btn-primary {
    background-color: #3498db;
    color: white;
    padding: 12 24;
    border-radius: 8;
}
</style>

调试应用 #

使用 Chrome DevTools #

bash
# 启动调试
ns debug android
ns debug ios

# 输出调试 URL
# 在 Chrome 中打开: chrome://inspect

控制台日志 #

typescript
// 在代码中添加日志
console.log('Debug message');
console.warn('Warning message');
console.error('Error message');

// 查看日志
ns debug android --log

断点调试 #

text
┌─────────────────────────────────────────────────────────────┐
│                    调试步骤                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 启动调试模式                                            │
│     ns debug android                                        │
│                                                             │
│  2. 打开 Chrome DevTools                                    │
│     chrome://inspect                                        │
│                                                             │
│  3. 点击 inspect 打开调试器                                 │
│                                                             │
│  4. 在 Sources 面板设置断点                                 │
│                                                             │
│  5. 触发断点进行调试                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

热重载 #

启用 HMR #

bash
# 启动带热重载的开发服务器
ns run android --hmr
ns run ios --hmr

HMR 工作原理 #

text
┌─────────────────────────────────────────────────────────────┐
│                    热重载流程                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  修改代码                                                    │
│      │                                                      │
│      ▼                                                      │
│  Webpack 编译                                               │
│      │                                                      │
│      ▼                                                      │
│  发送更新到设备                                              │
│      │                                                      │
│      ▼                                                      │
│  应用热更新                                                  │
│      │                                                      │
│      ▼                                                      │
│  无需重启即可看到变化                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

常见问题 #

应用无法启动 #

bash
# 清理项目
ns clean

# 重新安装依赖
rm -rf node_modules
npm install

# 重新运行
ns run android

模拟器问题 #

bash
# 列出可用设备
ns devices

# 重启 ADB 服务
adb kill-server
adb start-server

# 检查模拟器状态
adb devices

编译错误 #

bash
# 清理原生构建
ns platform remove android
ns platform add android

# 或使用 clean 命令
ns clean android

下一步 #

现在你已经创建了第一个 NativeScript 应用,接下来学习 项目结构,深入了解项目的组织方式!

最后更新:2026-03-29