且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Angular(4)中使用拆分的应用程序模块处理导入(客户端,服务器,共享)

更新时间:2022-05-12 06:14:55

带有Angular 4的 ASP.NET Core SPA >模板将 AppModule 分为三个文件,以便Webpack能够高效地编译客户端捆绑包(适合在浏览器中运行)和服务器端预渲染捆绑包(希望在Node中运行) 。

The ASP.NET Core SPA with Angular 4 template splits the AppModule into three files so that Webpack will be able to efficiently compile the client-side bundle (suitable for running in browsers) and the server-side prerendering bundle (meant for running in Node).

更具体地说,这种方法期望:

More specifically, such approach expects that:


  • 浏览器特定的模块和提供程序将放在 app.module.browser.ts 文件中。

服务器特定的模块和提供程序将放在 app.module.server.ts 文件中。

server-specific modules and providers will be put in the app.module.server.ts file.

无论执行上下文如何,任何需要的内容都会放入 app.module.shared.ts 文件。

anything needed regardless of the executing context will be put in the app.module.shared.ts file.

此将允许两个不同的引导周期:一个用于浏览器(共享 + 浏览器),另一个用于服务器(共享 + server )。两者之间的主要区别是,第一个从 @ angular / platform-b​​rowser 包导入 BrowserModule ,而后者从 @ angular / platform-server 包中导入 ServerModule ,这是呈现Angular应用程序页面所必需的

This will allow two different bootstrap cycles: one for the browsers (shared + browser) and one for the server (shared + server). The main difference between the two is that the first one imports the BrowserModule from the @angular/platform-browser package, while the latter imports the ServerModule from the @angular/platform-server package - which is required to render Angular app pages from the server.

也就是说,您应该将所有应用程序引用放入 app.module.shared.ts 文件,并使用 isomorphic 方法编写Angular代码-意味着无论执行上下文如何,它都可以工作:其余所有都应由默认的 Webpack 模板随附的配置,它将生成适当的客户端& JIT,AoT&的服务器构建服务器端渲染。

That said, you should put all your app references into the app.module.shared.ts file and write your Angular code using an isomorphic approach - meaning that it will work regardless of the executing context: all the rest should be handled by the default Webpack configuration shipped with the template, which will generate the appropriate client & server builds for JIT, AoT & server-side rendering.

有关(如何)开始在Angular中编写同构代码和/或识别执行环境并做出相应反应的一些(非常)基本信息,请查看此博客我在该主题上写的帖子。

For some (very) basic info about how to start writing isomorphic code in Angular and/or identify the executing environment and react accordingly, check out this blog post that I wrote on the topic.