NativeScript 项目结构 #

项目目录概览 #

text
┌─────────────────────────────────────────────────────────────┐
│                    项目结构总览                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  my-app/                                                    │
│  ├── app/                    # 应用源代码                   │
│  ├── App_Resources/          # 原生资源                     │
│  ├── node_modules/           # 依赖包                       │
│  ├── platforms/              # 原生平台代码(自动生成)      │
│  ├── package.json            # 项目配置                     │
│  ├── tsconfig.json           # TypeScript 配置              │
│  ├── nativescript.config.ts  # NativeScript 配置            │
│  └── webpack.config.js       # Webpack 配置                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

核心目录详解 #

app 目录 #

应用的主要源代码目录:

text
app/
├── app.xml                    # 应用入口页面
├── app.ts                     # 应用入口逻辑
├── app.css                    # 全局样式
├── app.module.ts              # Angular 模块(Angular 项目)
├── main.ts                    # 入口文件
│
├── components/                # 组件目录
│   ├── header/
│   │   ├── header.xml
│   │   ├── header.ts
│   │   └── header.css
│   └── footer/
│
├── pages/                     # 页面目录
│   ├── home/
│   │   ├── home.xml
│   │   ├── home.ts
│   │   └── home.css
│   ├── detail/
│   └── settings/
│
├── shared/                    # 共享模块
│   ├── models/               # 数据模型
│   ├── services/             # 服务
│   └── utils/                # 工具函数
│
├── assets/                    # 静态资源
│   ├── images/               # 图片
│   ├── fonts/                # 字体
│   └── data/                 # 数据文件
│
└── scss/                      # SCSS 样式文件
    ├── _variables.scss
    ├── _mixins.scss
    └── app.scss

App_Resources 目录 #

原生平台资源:

text
App_Resources/
├── Android/                   # Android 资源
│   ├── src/main/
│   │   ├── res/
│   │   │   ├── drawable/     # 图片资源
│   │   │   ├── mipmap-hdpi/  # 应用图标
│   │   │   ├── mipmap-mdpi/
│   │   │   ├── mipmap-xhdpi/
│   │   │   ├── mipmap-xxhdpi/
│   │   │   ├── mipmap-xxxhdpi/
│   │   │   └── values/
│   │   │       ├── colors.xml
│   │   │       └── strings.xml
│   │   └── AndroidManifest.xml
│   └── app.gradle            # Android 配置
│
└── iOS/                       # iOS 资源
    ├── Assets.xcassets/      # 资源目录
    │   ├── AppIcon.appiconset/
    │   └── LaunchImage.launchimage/
    ├── Info.plist            # iOS 配置
    └── LaunchScreen.storyboard

platforms 目录 #

自动生成的原生平台代码:

text
platforms/
├── android/                   # Android 原生项目
│   ├── app/
│   ├── build.gradle
│   └── settings.gradle
│
└── ios/                       # iOS 原生项目
    ├── <app-name>/
    ├── <app-name>.xcodeproj/
    └── Podfile

配置文件详解 #

package.json #

项目依赖和脚本配置:

json
{
  "name": "my-app",
  "version": "1.0.0",
  "main": "app/app.ts",
  "scripts": {
    "android": "ns run android",
    "ios": "ns run ios",
    "build:android": "ns build android",
    "build:ios": "ns build ios",
    "clean": "ns clean"
  },
  "dependencies": {
    "@nativescript/core": "~8.6.0",
    "@nativescript/angular": "~8.6.0",
    "@nativescript/theme": "~3.0.0"
  },
  "devDependencies": {
    "@nativescript/android": "~8.6.0",
    "@nativescript/ios": "~8.6.0",
    "@nativescript/webpack": "~5.0.0",
    "typescript": "~5.0.0"
  }
}

nativescript.config.ts #

NativeScript 配置:

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

export default {
    id: 'com.company.myapp',
    appPath: 'app',
    appResourcesPath: 'App_Resources',
    android: {
        v8Flags: '--expose_gc',
        markingMode: 'none'
    },
    ios: {
        discardUncaughtJsExceptions: true
    },
    webpack: {
        config: {
            // Webpack 配置
        }
    }
} as NativeScriptConfig;

tsconfig.json #

TypeScript 配置:

json
{
  "compilerOptions": {
    "module": "ESNext",
    "target": "ES2020",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "noEmitHelpers": true,
    "noEmitOnError": true,
    "skipLibCheck": true,
    "lib": ["ES2020"],
    "baseUrl": ".",
    "paths": {
      "~/*": ["app/*"]
    }
  },
  "include": ["app/**/*.ts"],
  "exclude": ["node_modules", "platforms"]
}

webpack.config.js #

Webpack 构建配置:

javascript
const { webpack } = require('@nativescript/webpack');

module.exports = (env) => {
    webpack.init(env);
    
    webpack.chainWebpack(config => {
        // 自定义配置
    });
    
    return webpack.resolveConfig();
};

应用入口 #

应用启动流程 #

text
┌─────────────────────────────────────────────────────────────┐
│                    应用启动流程                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 原生应用启动                                            │
│     │                                                       │
│     ▼                                                       │
│  2. NativeScript Runtime 初始化                             │
│     │                                                       │
│     ▼                                                       │
│  3. 加载 main.ts / app.ts                                   │
│     │                                                       │
│     ▼                                                       │
│  4. 初始化 Angular/Vue/React                                │
│     │                                                       │
│     ▼                                                       │
│  5. 加载根组件                                              │
│     │                                                       │
│     ▼                                                       │
│  6. 渲染界面                                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

纯 TypeScript 入口 #

app.ts

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

Application.run({
    moduleName: 'main-page'
});

// 应用事件
Application.on(Application.launchEvent, (args) => {
    console.log('App launched');
});

Application.on(Application.resumeEvent, (args) => {
    console.log('App resumed');
});

Application.on(Application.suspendEvent, (args) => {
    console.log('App suspended');
});

Application.on(Application.exitEvent, (args) => {
    console.log('App exited');
});

Angular 入口 #

main.ts

typescript
import { platformNativeScriptDynamic } from '@nativescript/angular';
import { AppModule } from './app.module';

platformNativeScriptDynamic().bootstrapModule(AppModule);

app.module.ts

typescript
import { NgModule } from '@angular/core';
import { NativeScriptModule } from '@nativescript/angular';
import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';

@NgModule({
    declarations: [AppComponent, HomeComponent],
    imports: [NativeScriptModule, AppRoutingModule],
    bootstrap: [AppComponent]
})
export class AppModule {}

Vue 入口 #

main.ts

typescript
import { createApp } from 'nativescript-vue';
import Home from './components/Home.vue';

const app = createApp(Home);
app.start();

资源管理 #

图片资源 #

text
┌─────────────────────────────────────────────────────────────┐
│                    图片资源组织                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  app/assets/images/                                         │
│  ├── logo.png               # 通用图片                      │
│  ├── logo@2x.png            # 2x 分辨率                     │
│  ├── logo@3x.png            # 3x 分辨率                     │
│  │                                                          │
│  ├── icons/                 # 图标                          │
│  │   ├── home.png                                          │
│  │   ├── settings.png                                      │
│  │   └── user.png                                          │
│  │                                                          │
│  └── backgrounds/           # 背景图                        │
│      ├── splash.png                                        │
│      └── header.png                                        │
│                                                             │
└─────────────────────────────────────────────────────────────┘

使用图片 #

xml
<!-- 使用图片 -->
<Image src="~/assets/images/logo.png" />

<!-- 使用图标字体 -->
<Label text="&#xf015;" class="fas" />

<!-- 使用网络图片 -->
<Image src="https://example.com/image.jpg" />

字体资源 #

text
app/assets/fonts/
├── FontAwesome.ttf
├── MaterialIcons.ttf
└── CustomFont.ttf

app.css

css
/* 注册字体 */
.fas {
    font-family: "Font Awesome 5 Free", "FontAwesome";
    font-weight: 900;
}

.material {
    font-family: "Material Icons";
}

样式组织 #

全局样式 #

app.css

css
/* 导入主题 */
@import '@nativescript/theme/css/core.css';
@import '@nativescript/theme/css/default.css';

/* 全局变量 */
Page {
    background-color: #f5f5f5;
}

ActionBar {
    background-color: #3498db;
    color: white;
}

/* 通用类 */
.text-center {
    text-align: center;
}

.p-10 { padding: 10; }
.p-20 { padding: 20; }
.m-10 { margin: 10; }
.m-20 { margin: 20; }

/* 按钮样式 */
.btn {
    padding: 12 24;
    border-radius: 8;
    font-size: 16;
}

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

.btn-secondary {
    background-color: #95a5a6;
    color: white;
}

SCSS 组织 #

text
app/scss/
├── _variables.scss           # 变量定义
├── _mixins.scss              # 混合宏
├── _buttons.scss             # 按钮样式
├── _forms.scss               # 表单样式
├── _typography.scss          # 排版样式
└── app.scss                  # 主样式文件

_variables.scss

scss
// 颜色
$primary: #3498db;
$secondary: #95a5a6;
$success: #2ecc71;
$danger: #e74c3c;
$warning: #f39c12;

// 字体大小
$font-size-xs: 12;
$font-size-sm: 14;
$font-size-base: 16;
$font-size-lg: 18;
$font-size-xl: 24;

// 间距
$spacing-xs: 4;
$spacing-sm: 8;
$spacing-base: 16;
$spacing-lg: 24;
$spacing-xl: 32;

app.scss

scss
@import 'variables';
@import 'mixins';
@import 'buttons';
@import 'forms';
@import 'typography';

// 全局样式
Page {
    background-color: #f5f5f5;
}

环境配置 #

环境文件 #

text
app/environments/
├── environment.ts            # 默认环境
├── environment.prod.ts       # 生产环境
└── environment.dev.ts        # 开发环境

environment.ts

typescript
export const environment = {
    production: false,
    apiUrl: 'https://api-dev.example.com',
    enableDebug: true
};

environment.prod.ts

typescript
export const environment = {
    production: true,
    apiUrl: 'https://api.example.com',
    enableDebug: false
};

使用环境变量 #

typescript
import { environment } from './environments/environment';

if (environment.enableDebug) {
    console.log('Debug mode enabled');
}

fetch(environment.apiUrl + '/users');

最佳实践 #

目录命名规范 #

text
┌─────────────────────────────────────────────────────────────┐
│                    命名规范                                  │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  目录名:小写 + 连字符                                      │
│  ✓ user-profile/                                            │
│  ✓ product-list/                                            │
│  ✗ UserProfile/                                             │
│  ✗ productList/                                             │
│                                                             │
│  组件文件:小写 + 连字符                                    │
│  ✓ user-card.xml                                            │
│  ✓ user-card.ts                                             │
│  ✓ user-card.css                                            │
│                                                             │
│  类名:大驼峰                                               │
│  ✓ UserCardComponent                                        │
│  ✓ ProductService                                           │
│                                                             │
└─────────────────────────────────────────────────────────────┘

模块化组织 #

text
app/
├── modules/
│   ├── auth/                 # 认证模块
│   │   ├── components/
│   │   ├── services/
│   │   ├── models/
│   │   └── auth.module.ts
│   │
│   ├── products/             # 产品模块
│   │   ├── components/
│   │   ├── services/
│   │   ├── models/
│   │   └── products.module.ts
│   │
│   └── users/                # 用户模块
│       ├── components/
│       ├── services/
│       ├── models/
│       └── users.module.ts
│
└── shared/                   # 共享模块
    ├── components/
    ├── services/
    └── shared.module.ts

下一步 #

现在你已经了解了项目结构,接下来学习 基础语法,掌握 NativeScript 的核心语法!

最后更新:2026-03-29