如何修复 Vue3 客户端版本的“unsafe-eval”错误?

The*_*Owl 8 javascript express content-security-policy vuejs3

我在我的应用程序中使用 Express、cors 和头盔。Vue3仅在客户端使用,库文件自托管在public文件夹中。我只是做

<script type="module" src="/public/lib/vue.esm-browser.js"></script>
Run Code Online (Sandbox Code Playgroud)

将模块添加到客户端。问题是,当我使用它时,它总是给我一个Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self'". 这个问题是昨天突然开始的,当我开始使用头盔和cors模块时,即使我注释掉这些模块,它仍然显示错误。我应该解决什么问题?

gra*_*nty 11

是的,vue.js 使用如下代码:

// detect possible CSP restriction
try {
  new Function('return 1')
} catch (e: any) {
  if (e.toString().match(/unsafe-eval|CSP/)) {
    warn(
      'It seems you are using the standalone build of Vue.js in an ' +
      'environment with Content Security Policy that prohibits unsafe-eval. ' +
      'The template compiler cannot work in this environment. Consider ' +
      'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
      'templates into render functions.'
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

这里你有 2 个选择:

  1. 预编译模板的使用,请参阅github 上的讨论

  2. 使用vue.runtime.js运行时版本而不是vue.js完整版本。

VueJS 有 2 个不同的版本:完整版本和运行时版本。仅 VueJS 完整版需要“unsafe-eval”;运行时版本不需要它。请参阅此处的详细信息。

仅运行时构建完全符合 CSP 标准。当使用 Webpack + vue-loader 或 Browserify + vueify 进行仅运行时构建时,您的模板将被预编译为在 CSP 环境中完美运行的渲染函数。请参阅Vue CSP 环境中的详细信息。

  • 也许值得指出的是,1 和 2 是相同的选项。如果没有预编译模板,Vue 的运行时构建不会为您做太多事情 (3认同)