reactjs - 如何在 React 中启用 webpack 内容安全策略?

标签 reactjs webpack create-react-app content-security-policy

Webpack 具有向其加载的所有脚本添加 nonce 的功能。

To activate the feature set a __webpack_nonce__ variable needs to be included in your entry script.

create React app生成的react app中的入口文件默认为index.js。所以我需要做的就是在条目文件中添加:

 // ...
__webpack_nonce__ = 'c29tZSBjb29sIHN0cmluZyB3aWxsIHBvcCB1cCAxMjM=';
// ...

最后一件事是启用 webpack CSP。

Please note that CSPs are not enabled by default. A corresponding header Content-Security-Policy or meta tag needs to be sent with the document to instruct the browser to enable the CSP. Here's an example of what a CSP header including a CDN white-listed URL might look like: Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;

但是,我遇到了错误

'__webpack_nonce__' is not defined

我尝试声明随机数。还是不行。

webpack_nonce is specified in the entry file and not in the configuration.

那么,我做错了什么?也许文档缺少有关该主题的一些关键信息?如何在 Webpack 中为 React 应用启用 CSP 功能?

最佳答案

如果您使用的是 create-react-app,那么可能是 ESLint 报告了错误。

尝试禁用该行:

__webpack_nonce__ = 'c29tZSBjb29sIHN0cmluZyB3aWxsIHBvcCB1cCAxMjM='; // eslint-disable-line no-undef

关于reactjs - 如何在 React 中启用 webpack 内容安全策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111013/

相关文章:

reactjs - React - 如何处理嵌套表单及其值

typescript - 模块导入返回空对象

javascript - 我如何像 React 一样在 Angular 2+ 中传递 Prop ?

javascript - Lodash 在 react 中对数据进行排序

javascript - useEffect 不去 if 语句

javascript - 项目中的 Foundation 6.4 JavaScript 无法正常工作,但外部 JS 可以

javascript - 如何导入webpack中非模块的库

reactjs - 无法使用 create-react-app 导入图像

javascript - 创建添加 CORS header 的 React App

javascript - React - 如何将本地镜像导入/获取到对象中