386

在实时 Web 服务器上捆绑 Angular(版本 2、4、6,...)以进行生产的最佳方法是什么。

请在答案中包含 Angular 版本,以便我们在它移动到更高版本时更好地跟踪。

4

12 回答 12

395

2 to 13(TypeScript) 与 Angular CLI

一次性设置

  • npm install -g @angular/cli
  • ng new projectFolder创建一个新应用程序

捆绑步骤

projectFolder/dist(/$projectFolder默认情况下为 v6+生成捆绑包) **

输出

13.2.4带有 CLI的 Angular13.2.4和不带 Angular 路由的选项 CSS的大小

  • dist/main-[es-version].[hash].js捆绑您的应用程序 [ES5 大小:132 KB 用于新的 Angular CLI 应用程序空,39 KB压缩]。
  • dist/polyfill-[es-version].[hash].bundle.js捆绑了 polyfill 依赖项(@angular,RxJS ...)[ES5 大小:37 KB 用于新的 Angular CLI 应用程序为空,12 KB压缩]。
  • dist/index.html应用程序的入口点。
  • dist/runtime-[es-version].[hash].bundle.jswebpack 加载器
  • dist/style.[hash].bundle.css样式定义
  • dist/assets从 Angular CLI 资产配置中复制的资源

部署

您可以使用启动本地 HTTP 服务器的命令来预览您的应用程序,ng serve --prod以便可以使用 http://localhost:4200 访问带有生产文件的应用程序。这对于生产使用是不安全的。

对于生产用途,您必须从dist您选择的 HTTP 服务器中的文件夹中部署所有文件。

于 2016-08-04T11:18:47.890 回答
59

2.0.1 Final使用 Gulp(TypeScript - 目标:ES5)


一次性设置

  • npm install (当目录为projectFolder时在cmd中运行)

捆绑步骤

  • npm run bundle (当目录为projectFolder时在cmd中运行)

    bundles 生成到projectFolder/bundles/

输出

  • bundles/dependencies.bundle.js[大小:~ 1 MB(尽可能小)]
    • 包含 rxjs 和角度依赖,而不是整个框架
  • bundles/app.bundle.js[大小:取决于你的项目,我的是~ 0.5 MB ]
    • 包含您的项目

文件结构

  • projectFolder / app /(所有组件、指令、模板等)
  • 项目文件夹/gulpfile.js

var gulp = require('gulp'),
  tsc = require('gulp-typescript'),
  Builder = require('systemjs-builder'),
  inlineNg2Template = require('gulp-inline-ng2-template');

gulp.task('bundle', ['bundle-app', 'bundle-dependencies'], function(){});

gulp.task('inline-templates', function () {
  return gulp.src('app/**/*.ts')
    .pipe(inlineNg2Template({ useRelativePaths: true, indent: 0, removeLineBreaks: true}))
    .pipe(tsc({
      "target": "ES5",
      "module": "system",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "removeComments": true,
      "noImplicitAny": false
    }))
    .pipe(gulp.dest('dist/app'));
});

gulp.task('bundle-app', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/* - [@angular/**/*.js] - [rxjs/**/*.js]', 'bundles/app.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});

gulp.task('bundle-dependencies', ['inline-templates'], function() {
  // optional constructor options
  // sets the baseURL and loads the configuration file
  var builder = new Builder('', 'dist-systemjs.config.js');

  return builder
    .bundle('dist/app/**/*.js - [dist/app/**/*.js]', 'bundles/dependencies.bundle.js', { minify: true})
    .then(function() {
      console.log('Build complete');
    })
    .catch(function(err) {
      console.log('Build error');
      console.log(err);
    });
});
  • projectFolder / package.json (与快速入门指南相同,仅显示捆绑所需的 devDependencies 和 npm-scripts)

{
  "name": "angular2-quickstart",
  "version": "1.0.0",
  "scripts": {
    ***
     "gulp": "gulp",
     "rimraf": "rimraf",
     "bundle": "gulp bundle",
     "postbundle": "rimraf dist"
  },
  "license": "ISC",
  "dependencies": {
    ***
  },
  "devDependencies": {
    "rimraf": "^2.5.2",
    "gulp": "^3.9.1",
    "gulp-typescript": "2.13.6",
    "gulp-inline-ng2-template": "2.0.1",
    "systemjs-builder": "^0.15.16"
  }
}

(function(global) {

  // map tells the System loader where to look for things
  var map = {
    'app':                        'app',
    'rxjs':                       'node_modules/rxjs',
    'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
    '@angular':                   'node_modules/@angular'
  };

  // packages tells the System loader how to load when no filename and/or no extension
  var packages = {
    'app':                        { main: 'app/boot.js',  defaultExtension: 'js' },
    'rxjs':                       { defaultExtension: 'js' },
    'angular2-in-memory-web-api': { defaultExtension: 'js' }
  };

  var packageNames = [
    '@angular/common',
    '@angular/compiler',
    '@angular/core',
    '@angular/forms',
    '@angular/http',
    '@angular/platform-browser',
    '@angular/platform-browser-dynamic',
    '@angular/router',
    '@angular/router-deprecated',
    '@angular/testing',
    '@angular/upgrade',
  ];

  // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' }
  packageNames.forEach(function(pkgName) {
    packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
  });

  var config = {
    map: map,
    packages: packages
  };

  // filterSystemConfig - index.asp's chance to modify config before we register it.
  if (global.filterSystemConfig) { global.filterSystemConfig(config); }

  System.config(config);

})(this);
  • projetcFolder / dist-systemjs.config.js(只是显示了与 systemjs.config.json 的区别)

var map = {
    'app':                        'dist/app',
  };
  • projectFolder / index.html (production) -脚本标签的顺序很关键。在捆绑标签之后放置dist-systemjs.config.js标签仍然允许程序运行,但依赖捆绑将被忽略,并且依赖将从node_modules文件夹中加载。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <base href="/"/>
  <title>Angular</title>
  <link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>

<my-app>
  loading...
</my-app>

<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>

<script src="node_modules/zone.js/dist/zone.min.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.js"></script>

<script src="dist-systemjs.config.js"></script>
<!-- Project Bundles. Note that these have to be loaded AFTER the systemjs.config script -->
<script src="bundles/dependencies.bundle.js"></script>
<script src="bundles/app.bundle.js"></script>

<script>
    System.import('app/boot').catch(function (err) {
      console.error(err);
    });
</script>
</body>
</html>
  • projectFolder / app / boot.ts是引导程序所在的位置。

我能做的最好的:)

于 2016-06-17T06:32:11.710 回答
22

Angular 2 和 Webpack(没有 CLI 设置)

1- Angular2 团队的教程

Angular2 团队发布了使用 Webpack的教程

我创建了教程中的文件并将其放置在一个小型GitHub 种子项目中。因此,您可以快速尝试工作流程。

说明

  • npm 安装

  • npm 开始。为了发展。这将创建一个虚拟的“dist”文件夹,该文件夹将在您的本地主机地址上重新加载。

  • npm 运行构建。用于生产。“这将创建一个物理“dist”文件夹版本,而不是可以发送到网络服务器。dist 文件夹是 7.8MB,但实际上只需要 234KB 就可以在网络浏览器中加载页面。

2 - Webkit 入门工具包

这个Webpack Starter Kit提供了比上述教程更多的测试功能,并且看起来很受欢迎。

于 2016-10-08T20:41:50.677 回答
16

使用 SystemJs builder 和 gulp 的 Angular 2 生产工作流程

Angular.io 有快速入门教程。我复制了本教程并扩展了一些简单的 gulp 任务,将所有内容捆绑到 dist 文件夹,可以复制到服务器并像那样工作。我尝试优化一切以在 Jenkis CI 上正常运行,因此 node_modules 可以被缓存并且不需要复制。

Github 上带有示例应用程序的源代码:https ://github.com/Anjmao/angular2-production-workflow

生产步骤
  1. 清理 typescripts 编译的 js 文件和 dist 文件夹
  2. 在 app 文件夹中编译打字稿文件
  3. 使用 SystemJs 捆绑器将所有内容捆绑到 dist 文件夹,并生成哈希以进行浏览器缓存刷新
  4. 使用 gulp-html-replace 将 index.html 脚本替换为捆绑版本并复制到 dist 文件夹
  5. 将 assets 文件夹中的所有内容复制到 dist 文件夹

节点:虽然您总是可以创建自己的构建过程,但我强烈建议使用 angular-cli,因为它具有所有需要的工作流程并且现在可以完美运行。我们已经在生产中使用它,并且完全没有 angular-cli 的任何问题。

于 2016-09-18T18:59:20.933 回答
15

Angular CLI 1.xx(适用于 Angular 4.xx、5.xx)

这支持:

  • Angular 2.x 和 4.x
  • 最新的 Webpack 2.x
  • Angular AoT 编译器
  • 路由(正常和懒惰)
  • SCSS
  • 自定义文件捆绑(资产)
  • 其他开发工具(linter、单元和端到端测试设置)

初始设置

ng 新项目名称 --routing

您可以添加--style=scssSASS .scss 支持。

您可以添加--ng4使用 Angular 4 而不是 Angular 2。

创建项目后,CLI 将自动npm install为您运行。如果您想改用 Yarn,或者只是想在没有安装的情况下查看项目骨架,请在此处查看如何操作

捆绑步骤

在项目文件夹内:

ng build -prod

在当前版本中,您需要--aot手动指定,因为它可以在开发模式下使用(尽管由于速度慢,这不实用)。

这也为更小的包执行 AoT 编译(没有 Angular 编译器,而是生成编译器输出)。如果您使用 Angular 4,则使用 AoT 的包要小得多,因为生成的代码更小。
您可以在开发模式下使用 AoT 测试您的应用程序(源地图,没有缩小),并通过运行ng build --aot.

输出

默认输出目录是./dist,尽管它可以在./angular-cli.json.

可部署文件

构建步骤的结果如下:

(注意:<content-hash>指的是文件内容的哈希/指纹,这是一种缓存破坏方式,这是可能的,因为 Webpack 自己编写script标签)

  • ./dist/assets
    按原样复制的文件来自./src/assets/**
  • ./dist/index.html
    ./src/index.html, 将 webpack 脚本添加到它之后
    源模板文件可在./angular-cli.json
  • ./dist/inline.js
    小型 webpack 加载器/polyfill
  • ./dist/main.<content-hash>.bundle.js
    包含所有生成/导入的 .js 脚本的主 .js 文件
  • ./dist/styles.<content-hash>.bundle.js
    当您使用 CLI 方式的 CSS 的 Webpack 加载器时,它们在此处通过 JS 加载

在旧版本中,它还创建了 gzipped 版本来检查它们的大小和.mapsourcemaps 文件,但随着人们不断要求删除这些文件,这种情况不再发生。

其他文件

在某些其他情况下,您可能会发现其他不需要的文件/文件夹:

  • ./out-tsc/
    ./src/tsconfig.jsonoutDir
  • ./out-tsc-e2e/
    ./e2e/tsconfig.jsonoutDir
  • ./dist/ngfactory/
    来自 AoT 编译器(从 beta 16 开始,如果不分叉 CLI,则无法配置)
于 2016-10-06T10:39:05.623 回答
5

到今天为止,我仍然认为 Ahead-of-Time Compilation 食谱是生产捆绑的最佳配方。你可以在这里找到它:https ://angular.io/docs/ts/latest/cookbook/aot-compiler.html

到目前为止,我对 Angular 2 的体验是,AoT 创建了最小的构建,几乎没有加载时间。最重要的是这里的问题 - 您只需要将几个文件发送到生产环境。

这似乎是因为 Angular 编译器不会随生产版本一起提供,因为模板是“提前”编译的。看到您的 HTML 模板标记转换为很难逆向工程为原始 HTML 的 javascript 指令也非常酷。

我制作了一个简单的视频,我在其中演示了开发与 AoT 构建中 Angular 2 应用程序的下载大小、文件数量等 - 你可以在这里看到:

https://youtu.be/ZoZDCgQwnmQ

您可以在此处找到视频中使用的源代码:

https://github.com/fintechneo/angular2-templates

于 2017-01-13T19:55:01.897 回答
3
        **Production build with

         - Angular Rc5
         - Gulp
         - typescripts 
         - systemjs**

        1)con-cat all js files  and css files include on index.html using  "gulp-concat".
          - styles.css (all css concat in this files)
          - shims.js(all js concat in this files)

        2)copy all images and fonts as well as html files  with gulp task to "/dist".

        3)Bundling -minify angular libraries and app components mentioned in systemjs.config.js file.
         Using gulp  'systemjs-builder'

            SystemBuilder = require('systemjs-builder'),
            gulp.task('system-build', ['tsc'], function () {
                var builder = new SystemBuilder();
                return builder.loadConfig('systemjs.config.js')
                    .then(function () {
                        builder.buildStatic('assets', 'dist/app/app_libs_bundle.js')
                    })
                    .then(function () {
                        del('temp')
                    })
            });


    4)Minify bundles  using 'gulp-uglify'

jsMinify = require('gulp-uglify'),

    gulp.task('minify', function () {
        var options = {
            mangle: false
        };
        var js = gulp.src('dist/app/shims.js')
            .pipe(jsMinify())
            .pipe(gulp.dest('dist/app/'));
        var js1 = gulp.src('dist/app/app_libs_bundle.js')
            .pipe(jsMinify(options))
            .pipe(gulp.dest('dist/app/'));
        var css = gulp.src('dist/css/styles.min.css');
        return merge(js,js1, css);
    });

5) In index.html for production 

    <html>
    <head>
        <title>Hello</title>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="utf-8" />

       <link rel="stylesheet" href="app/css/styles.min.css" />   
       <script type="text/javascript" src="app/shims.js"></script>  
       <base href="/">
    </head>
     <body>
    <my-app>Loading...</my-app>
     <script type="text/javascript" src="app/app_libs_bundle.js"></script> 
    </body>

    </html>

 6) Now just copy your dist folder to '/www' in wamp server node need to copy node_modules in www.
于 2017-01-10T08:42:32.043 回答
2

您可以github使用 angular-cli-ghpages部署您的 Angular 应用程序

查看链接以了解如何使用此 cli 进行部署。

github部署的网站通常会存储在某个分支中

gh页面

use 可以克隆 git 分支并像使用服务器中的静态网站一样使用它

于 2017-09-01T07:26:44.297 回答
1

“最佳”取决于场景。有时您只关心最小的单个捆绑包,但在大型应用程序中您可能不得不考虑延迟加载。在某些时候,将整个应用程序作为单个包提供服务变得不切实际。

在后一种情况下,Webpack 通常是最好的方式,因为它支持代码拆分。

对于单个捆绑包,我会考虑 Rollup,或者如果你觉得勇敢的话,我会考虑 Closure 编译器 :-)

我已经创建了我在这里使用过的所有 Angular 捆绑器的示例:http ://www.syntaxsuccess.com/viewarticle/angular-production-builds

代码可以在这里找到:https ://github.com/thelgevold/angular-2-samples

角度版本:4.1.x

于 2017-05-23T01:53:24.080 回答
1

ng serve 用于为我们的应用程序提供开发服务。生产呢?如果我们查看我们的 package.json 文件,我们可以看到我们可以使用一些脚本:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build --prod",
  "test": "ng test",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

构建脚本使用带有 --prod 标志的 Angular CLI 的 ng 构建。现在让我们试试吧。我们可以通过以下两种方式之一来做到这一点:

# 使用 npm 脚本

npm run build

# 直接使用cli

ng build --prod

这次我们得到了四个文件而不是五个。--prod 标志告诉 Angular 让我们的应用程序体积更小。

于 2019-12-31T06:13:11.680 回答
0

只需在一分钟内使用 webpack 3 设置 angular 4,您的开发和生产 ENV 包就会准备就绪,没有任何问题,只需按照下面的 github doc

https://github.com/roshan3133/angular2-webpack-starter

于 2017-09-03T12:04:29.530 回答
0

请在当前项目目录中尝试以下 CLI 命令。它将创建 dist 文件夹包。因此您可以上传 dist 文件夹中的所有文件以进行部署。

ng build --prod --aot --base-href。

于 2019-05-15T07:42:29.600 回答