Angular CLI是一个命令行界面工具,它可以创建项目、添加文件以及执行一大堆开发任务,比如测试、打包和发布。
相比手动进行这些操作,Angular CLI能让开发更加简单快捷。
前提
CLI和生成的项目有一些依赖,需要Node6.9.0或更高版本,NPM3或更高版本。
安装
npm install -g @angular/cli
使用
ng help
生成Angular项目并通过开发服务器启动
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve
在浏览器中输入http://localhost:4200/
可以看到项目成功启动。如果你修改了源文件,页面会自动刷新。
可以使用两个命令行选项配置开发服务器使用的默认HTTP主机和端口:
ng serve --host 0.0.0.0 --port 4201
生成组件、指令、 管道和服务
你可以使用ng generate
或者ng g
命令生成Angular组件:
ng generate component my-new-component
ng g component my-new-component # using the alias
# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
# if in the directory src/app you can also run
ng g component feature/new-cmp
# and your component will be generated in src/app/feature/new-cmp
完整命令参考下表:
Scaffold | Usage |
---|---|
Component | ng g component my-new-component |
Directive | ng g directive my-new-directive |
Pipe | ng g pipe my-new-pipe |
Service | ng g service my-new-service |
Class | ng g class my-new-class |
Guard | ng g guard my-new-guard |
Interface | ng g interface my-new-interface |
Enum | ng g enum my-new-enum |
Module | ng g module my-module |
angular-cli会自动将生成的组件、管道和指令添加到app.module中,如果你希望将这些添加到自定义的模块中,参考如下步骤:
ng g module new-module
创建新模块ng g component new-module/new-component
在模块中创建组件,模块会自动打包这个组件
使用实例
创建项目
项目名称为ngx-test1,略作等待可以看到项目创建成功。
创建模块和其包含的组件
- 输入命令
cd ngx-test1
进入ngx-test1目录 - 输入命令
ng g module pages
会自动创建src/app/pages
目录并在这个目录下创建pages模块。 - 输入命令
ng g component pages
,Angular CLI会帮我们在src/app/pages
目录下创建pages组件,共4个文件,并自动将pages组件添加到pages模块中
同上,创建auth模块
在src/app/pages/front-end
目录下创建front-end模块,并继续创建back-end,database,home等模块。
在src/app/
创建@core和@theme文件夹
在VSCode中查看项目文件结构,可看到src中的结构如下,项目的文件结构雏形就出来了。