Angular4 从创建到发布生产环境

环境简介

  • Angular4 @angular/cli
  • 开发环境
    Mac + WebStorm
  • 生产环境
    Ubuntu + Nginx

使用 @angular/cli创建angular4项目

  • 必备条件:
    1. Node.js 6.9.x以上
    2. npm 3.x.x以上
  • 安装
    npm install -g @angular/cli
  • 创建项目
    ng new my-app
  • 启动
    cd my-app
    ng serve --open #--open 自动打开浏览器,不是必须
    
  • 测试项目
    浏览器访问Url即可
    http://localhost:4200

发布

angular4可以使用多种方式编译发布:

  • tsc
  • aot
  • webpack2

tsc

tsc是angular默认的发布方式,这种方式会将所有文件打包、压缩、混淆,但打包出来的文件仍然很大,因为这个打包将很多没有用到的库文件也一起打包了。

#使用angular/cli自带的tsc打包
cd my-app
ng build #编译并打包
ng build --prod #编译并打包、混淆为生产环境

npm run build #与上面同理
npm run build --prod #与上面同理

AoT

预AoT编译是angular提供的另外一套编译方式。可以配合Tree Shaking工具进行代码的精简、压缩、混淆。
预AoT编译官方教程

部署到Ubuntu Nginx

使用ng build --prod编译发布后,项目中的dist文件夹就是发布编译好的生产文件。
dist文件夹中只包含一个index.html文件、一些JS文件和assert文件夹。原因是angular已经将所有的组件编译到了main.js文件中,包括html、css。实际上这时我们就可以把这个dist文件放到任何服务器中使用了。

Nginx

安装好nginx之后,打开nginx的站点配置文件

vim /etc/nginx/sites-available/default

找到server节点下的下面这些内容

server{
        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }
}

将内容修改为

server{
        root /var/www/dist; # dist文件夹为之前编译并打包的文件夹

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html; # 这里定义的是nginx默认首页

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ /index.html; #因为angular将所有的组件全部打包到了js里面,只留了一个index.html,所以只需要将所有的http请求指向index.html即可
        }
}

重启并访问服务器的地址。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值