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/