如何在 Angular 5 Universal 应用程序中排除浏览器模块

Tom*_*eck 4 angular-cli angular-universal angular angular5

我正在尝试创建一个 Angular Universal 应用程序,在构建时构建特定路由,将 AppShell 注入 Index.html 页面,作为尽快在用户面前获取有意义内容的一种方式(当 Angular 应用程序正在下载时)。我正在按照Angular 大学的说明进行操作,并按照说明进行操作。但是,当我系统地将现有应用程序的功能添加到此测试应用程序中时,我遇到了“意外令牌导入”错误,该错误源于浏览器应用程序所需的第 3 方插件,但对于非常简单的服务器应用程序我不需要我正在尝试构建并注入 Index.html 作为我的 App Shell。

我花了几个小时研究这个,发现有很多帖子推荐 webpack,但是,我使用的是 Angular CLI。我不确定如何将 webpack 与 Angular CLI 构建过程结合起来。

我发现这篇文章似乎表明您可以使用 tsconfig.server.json 的排除部分从 Angular Universal 构建中排除模块。我已经尝试在 tsconfig.server.json 中列出要排除的模块,但是,我仍然收到“意外的令牌导入”错误。

我有一条路线需要构建并注入到我的索引页面中。我希望/认为我应该能够排除我的绝大多数应用程序,因为它与创建 AppShell 无关。我认为 Angular 应该简单地构建为服务器应用程序注册的路由所需的必要位。

我使用的是 Angular CLI 版本 1.7.3 和 Angular 版本 5.2.4。

有没有人知道如何从构建到 Angular Universal 应用程序中排除不必要的模块?

谢谢你的时间。

dar*_*614 6

您可以尝试为浏览器专门创建第三个模块。此 BrowserModule 将包含您在浏览器中所需的一切。

import { NgModule } from '@angular/core';    
import { AppModule} from './app.module';
import { AppComponent } from './app.component';
// other browser exlusive imports

@NgModule({
  imports: [
    // browser exlusive imports
    AppModule
  ],
  bootstrap: [AppComponent]
})
export class AppBrowserModule { }
Run Code Online (Sandbox Code Playgroud)

然后你在 main.ts 文件中引导这个新模块而不是你的 AppModule。此 StackOverflow 问题中也讨论了此方法:在 Angular 中需要 BrowserAnimationsModule 但在 Universal 中出现错误
此处要在服务器上排除的模块是 BrowserAnimationsModule,但对于您不需要的任何其他模块,它应该几乎相同服务器。
如果您需要将脚本包含在浏览器中,您可以将它们导入到 main.ts 中,并且它们应该可用于您的整个应用程序。

如果您需要检查您是否在浏览器上,您可以从 angular 使用 isPlatformBrowser:https
://angular.io/api/common/isPlatformBrowser @Optional 装饰器也可以非常方便(https://angular.io/api /核心/可选),如果您想通过依赖注入仅在浏览器上的组件或服务之一中包含某些内容。
您可能需要这些来防止由于服务器呈现的应用程序上缺少文件而导致的错误。

您所描述的导入错误是由第三方库未正确构建其库引起的。解决这个问题的一个简单方法是在抛出这些错误的文件上使用 babel。例如,如果您有一个名为“failingPackage”的包:

babel ./node_modules/failingPackage -d ./node_modules/failingPackage --presets es2015
Run Code Online (Sandbox Code Playgroud)

您基本上是在编译损坏包的所有文件,并用新文件覆盖旧文件。我告诉您这种方法,因为您可能会在要在服务器呈现的应用程序上使用的包上遇到此错误。

您可以在此处阅读有关此问题的更多信息:https : //github.com/angular/angular-cli/issues/7200

此处讨论了使用 babel 的解决方案:https : //github.com/SebastianM/angular-google-maps/issues/1052 全部归功于 Anthony Nahas。

或者,您可以尝试此解决方案:Angular4 + Universal + ng-bootstrap 出现“Unexpected token import”错误

  • 使用 ng eject 创建一个 webpack.config.js
  • 安装 webpack-node-externals
  • 将 webpack.config.js 的外部部分中的失败包列入白名单