angular 模块的理解
- 前端模块化的理解
- Angular Module 有什么作用
- 如何定义一个Angular module @ngModule()装饰器的使用
- Angular 本身有哪些常用的Module
- 在工程中实际运用Module
Angular Module
前端模块化的发展
JavaScript脚本语言的推出处理浏览器人机交互,可随着web应用的交互复杂化,丰富化,脚本代码的可组织重用性、隔离性、可维护性、版本管理、依赖管理等问题就浮现出来,自然而然的javascript 就走上了模块化发展的道路。
最初的javascript模块化特性实现
最早使用 Script 标签、组织目录文件,闭包,利用对象模拟命名空间等方法来实现一个重用性,隔离性的特性
var app = {};app.hello = {sayHi: function(){console.log('Hi');},sayHello: function(){console.log('Hello');}}
CommonJS模块化规范的制定
- 上面的这些方法并不能很好的解决可组织重用性、隔离性、可维护性、版本管理、依赖管理这些问题,09年CommonJS 社区以此发展出了很多的模块化规范(CMD,AMD之类的)(node.js 基于CommonJs规范发布),这些规范以及加载库的提出解决了前端依赖管理等一些问题,
模块化写法浏览器并不能直接执行, webpack 工具的出现解决打包编译的问题。 ```bash //hello.js function hello(){ this.sayHi = function(){ console.log( “Hello foo” ); }
this.sayHello = function(){ console.log( “Hello bar” ); } }
module.exports.hello = hello;
var hello = require(“./hello”).hello, test = new hello(); test.hello()
<a name="feCXt"></a>#### 原生语言层面的支持- ES6 中将Module作为标准模块化规范,ES6 module与CommonJS CMD 规范的差异???<a name="Jm3jC"></a>#### Angular Module- Angular 定义了@NgModule() 装饰器 ,为一个组件集声明了编译的上下文环境,(意味着angular Module 是angular 打包的最小单位)它专注于某个应用领域、某个工作流或一组紧密相关的能力,它可以将其组件和一组相关代码(如服务)关联起来,形成功能单元。- 像 JavaScript 模块一样,NgModule 也可以从其它 NgModule 中导入功能,并允许导出它们自己的功能供其它 NgModule 使用- 得益于angular module 的设计,配置了异步模块后,angular cli comper 会自动把模块切分成独立的chunk,其他的框架需要webpack 去配置代码分割<a name="LXSuI"></a>### Angular @NgModule的使用```typescriptimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { AppRoutingModule } from './app-routing.module';import { AppComponent } from './app.component';import { LifecycleComponent } from "./lifecycle/lifecycle.component";import { MainComponent } from "./main/main.component";import { OnChangeComponent } from "./onChange/on-change.component";import { SetterComponent } from "./setter/setter.component";import { ViewChildComponent } from "./viewChild/view-child.component";import { MyInputComponent } from "./my-input/my-input.component";import { TemplateOutletComponent } from "./template-outlet/template-outlet.component";@NgModule({/*** 那些属于本 NgModule 的组件、指令、管道* */declarations: [AppComponent,MainComponent,LifecycleComponent,OnChangeComponent,SetterComponent,ViewChildComponent,MyInputComponent,TemplateOutletComponent],/*** 用来导入外部模块* */imports: [BrowserModule,AppRoutingModule,FormsModule],/*** 需要使用的 Service 都放在这里* */providers: [],/*** 应用的主视图,称为根组件。它是应用中所有其它视图的宿主。只有根模块才应该设置这个 bootstrap 属性* */bootstrap: [ AppComponent ]})export class AppModule {}/*** 应用的主视图,称为根组件。它是应用中所有其它视图的宿主。只有根模块才应该设置这个 bootstrap 属性* */
