compileComponents
的文档无助地只说明这一点:
Compile components with a
templateUrl
for the test's NgModule. It is necessary to call this function as fetching urls is asynchronous.
然而,这并没有解释在什么情况下“有必要”调用这个函数,也没有解释不这样做的后果。我目前正在开发的应用程序对具有 templateUrl
的组件进行了单元测试,这些测试涉及使用 By.css
查看 DOM,但它们似乎工作正常,即使我们从不在代码库的任何地方调用 compileComponents
。与此同时,互联网上还有其他帖子,例如https://github.com/angular/angular-cli/pull/4757。 ,这表明调用 compileComponents
不是必需的。
什么情况下应该调用这个方法,为什么?
最佳答案
In what circumstances should I call this method, and why?
如果您使用的是 webpack(如果配置正确),构建会将 templateUrl
编译成内联 template
和 styleUrls
到样式
。所以没有必要 compileComponents
因为它就像你正在使用 template
和 styles
即使你不是。
例如,如果您使用的是 SystemJS(或者您没有执行此预编译/转换的其他构建步骤),则不会发生这种情况。 Angular 需要发出 XHR 请求来检索外部模板和外部样式,然后进行编译。在这里,您需要compileComponents
。
这在 Angular v2 testing docs 中说明
WebPack developers need not call
compileComponents
because it inlines templates and css as part of the automated build process that precedes running the test.
以及在 Angular v13 的最新文档中与调用 compileComponents 相关:
Ignore this section if you only run tests with the CLI ng test command because the CLI compiles the application before running the tests.
关于javascript - 我应该什么时候调用 compileComponents,我怎么能不这样做呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43608398/