【chrome扩展开发】vue-i18n使用问题及解决方案

记录chrome扩展开发时调用vue-i18n的一些问题和解决方法

环境

  • vue: ^3.3.4
  • vue-i18n: ^9.2.2
  • vite: ^4.4.8

错误1

Uncaught (in promise) 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' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:*".

解决方案1:
方案来源:

  • https://github.com/intlify/bundle-tools/issues/23#issuecomment-893353418
  • https://github.com/intlify/bundle-tools/tree/main/packages/vue-i18n-loader#why-do-we-need-to-require-the-configuration

这个方法虽然可以解决报错问题,但是t函数还是无法正常使用,如果只是简单的语言调用可以使用tm函数

<script setup>
import {useI18n} from 'vue-i18n'
const {tm} = useI18n()
</script>

<template>
	<div>
		{{ tm('test') }}
	</div>
</template>

解决方案2:
方案来源:https://www.cnblogs.com/guangzan/p/14999292.html

使用 vite 插件 vite-plugin-vue-i18n 处理这个问题

npm i --save-dev @intlify/vite-plugin-vue-i18n

# 包文档: https://www.npmjs.com/package/@intlify/vite-plugin-vue-i18n (停更)
# 包作者提醒:
# This plugin support until Vite 3. If you would like to use on Vite 4, please use @intlify/unplugin-vue-i18n

npm i --save-dev @intlify/unplugin-vue-i18n
# 包文档: https://www.npmjs.com/package/@intlify/unplugin-vue-i18n

错误2

You are running the esm-bundler build of vue-i18n. It is recommended to configure your bundler to explicitly replace feature flag globals with boolean literals to get proper tree-shaking in the final bundle.

解决方案:

// vite.config.ts
resolve: {
  alias: {
    // ...
    'vue-i18n': 'vue-i18n/dist/vue-i18n.runtime.esm-bundler.js'
  },
},

其他相关文献:

  • 【vue-i18n踩坑】The message format compilation is not supported in this build.
  • 【VUE】vue-i18n: Uncaught SyntaxError: Not available in legacy mode

你可能感兴趣的:(Web前端,chrome,vue.js,前端)