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

How to fix "unsafe-eval" error with Vue3 for the client-side version?

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

<script type="module" src="/public/lib/vue.esm-browser.js"></script>

将模块添加到客户端。问题是当我使用它时,它一直给我一个 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'"。这个问题是昨天突然出现的,当我开始使用helmet和cors模块时,即使我注释掉了这些模块,它仍然显示错误。我应该修复什么?

是的,vue.js使用了这样一段代码:

  // detect possible CSP restriction
  try {
    new Function('return 1');
  } catch (e) {
    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.'
      );
    }
  }

这里有2个选项:

  1. 预编译模板的使用,参见discussion at github

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

VueJS 有两个不同的版本:完整版和运行时版。 'unsafe-eval' 只有完整版的 VueJS 才需要;运行时版本不需要它。查看详细信息 here

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