Angular 常用 serve/build 命令及自定义扩展命令
前言
在Angular项目中,AngularCLI内置了`ng build`、`ng serve`等命令。我们想要执行特定功能的build和serve命令的时候,我们需要每次启动都要在后面跟比较长的参数,非常繁琐。AngularCLI项目本身也是也是一个npm项目。在项目中的package.json中的script对应的命令,我们可以通过npm执行命令来代替冗长的命令。eg:
我们可以用
npm run start
来代替
ng serve
常用启动和编译命令(更新中)
ng serve
**ng serve --prod --aot 最小化打包启动**
--prod参数后,angular-cli会把用不到的包都删掉,而–aot参数是让angular-cli启动预编译特性。
**ng serve --proxy-config proxy.conf.json**
指定后台转发地址,即nginx的proxy\_pass代理功能。开发时为避免ajax跨域,需要指定后台接口的转发地址。
`proxy.config.json`文件示例如下:
{
"/api": { // 匹配前缀
"target": "http://localhost:3000", // 转发地址
"secure": false
}
}
**ng serve --base-href ./**
指定站点的起始路径,如果你希望你的站点根路径为 [www.abc.com/mypath/][www.abc.com_mypath] ,需要这样设置:
ng build --base-href /mypath/
ng build
**ng build --prod --aot 最小化编译打包**
--prod参数后,angular-cli会把用不到的包都删掉,而–aot参数是让angular-cli启动预编译特性。
**ng build --target**
指定构建的目标,默认值是`development`,如果指定为`production`,构建时会加入treeshaking、代码压缩混淆等。下面两条等价:
ng build --target=production
ng build --prod
ng build --environment
指定应用执行环境。CLI会根据指定的值加载对应的环境配置文件。下面两句等价:
ng build --environment=prod
ng build --env=prod
构建时会加载`angular-cli.json`指定的环境配置文件:
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
**ng build --delete-output-path**
`ng build --delete-output-path = true`(默认)build时清空目标文件夹
`ng build --delete-output-path = false` build时替换目标文件夹重复命名文件
ng lint
调用tslint运行整个项目,获取警告和错误,来指出代码中不规范的地方
ng lint -force -fix -format 帮助格式修复
拓展:
CLI其实内置了几个快捷命令来对应默认生成的配置如`ng serve`、`ng build`等等,如果是我们额外自定义的配置,则可以使用`ng run <project>:<architect>[:configurations] [其他配置]`命令来实现,其中`project`和`architect`为必填,`configurations`为选填。
比如我们在angular.json/angular-cli.json简单额外自定义一个本地运行的服务器命令:
{
"architect":{
"myServe":{
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "xxxx:build",
"port": 8800
},
"configurations": {
"port1": {
"port": 8801
},
"port2": {
"port": 880
}
}
}
}
}
配置使用了内置的运行本地服务器程序,然后使用默认的build配置,加上自定义的运行端口,另外加上两个不同模式,运行不同端口。
使用`ng run xxxx:myServe`可以正常运行本地服务器跑项目,端口是8800
使用`ng run xxxx:myServe:port1`端口是8801
当然,我们还可以直接使用额外的命令行配置直接覆盖已经定义的配置:
`ng run xxxx:myServe:port1 --port=8808`
**package.json依赖管理dependencies中`^`和`~`的区别**
`~`的意思是匹配最近的小版本
比如`~4.0.2`将会匹配所有的4.0.x版本,但不匹配4.1.0
`^`的意思是最近的一个大版本
比如`^4.0.2` 将会匹配 所有 4.x.x, 但不包括5.x.x
还没有评论,来说两句吧...