且构网

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

如何解决“违反CSP指令:" default-src'self'在Angular 8中?

更新时间:2021-11-22 05:43:50

我认为这可以回答我的问题:

I think this can be an acceptable answer for my question:

首先,我的建议是使用 styleUrls 远离.Angular将使用< style> 元素将组件的样式注入DOM.其次,如果可能,您应该了解/询问部署服务器/环境上的CSP策略.我为解决该问题所做的工作(我的项目规模很小,只有几个组件):

First of all, my recommendation is stay away from using styleUrls. Angular will inject styles of your component into the DOM using <style> element. Secondly, if it's possible, you should know / ask for the CSP policy on the deployment server/environment. What I have been doing to resolve the issue (my project is reletively small with just a couple dozen of components):

  1. 复制(一对一)组件的相对链接,并将其放入 styles 属性的 angular.json 中.这是因为Angular会将此属性中的所有样式捆绑为单个 css/scss 文件.我一个一个地复制,因为 css/scss 文件最初设计为可与Angular View Encapsulation一起使用.将它们全部聚集到一个地方可能会引入意外的问题,这会破坏UI.每当复制组件样式并放入 styles 时,我都会检查UI是否因此而中断.如果发生此类问题,这将有助于我缩小根本原因.

  1. Copy (one by one) relative link of components, put them into angular.json, in styles attribute. This is because Angular will bundle all styles in this attribute as a single css/scss file. I copy one by one because the css/scss file was designed to work with Angular View Encapsulation in the first place. Gathering all of them into one place might introduct unexpected issue, this will break the UI. Whenever copy a component style and put into styles, I check if the UI breaks because of that. This will help me narrow down the root cause if such issue happens.

对于每个组件,将其组件样式文件的相对路径复制到 styles 后,我将 @Component 中的 styleUrls 删除.这样可以防止Angular将< style> 注入DOM.

For each component, after copy its component style file's relative path into styles, I remove styleUrls in @Component. This prevents Angular from injecting <style> into the DOM.

注意事项:

  • 将所有样式收集到一个文件中并立即加载它们可能会导致性能问题.幸运的是,我的公司项目相对较小.
  • 现在您需要记录使样式在项目中起作用的新方法.