【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:

方案来源:

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

javascript 复制代码
<script setup>
import {useI18n} from 'vue-i18n'
const {tm} = useI18n()
</script>

<template>
	<div>
		{{ tm('test') }}
	</div>
</template>
javascript 复制代码
// 在createI18n时,增加一个导出方法,来简单解决`t`函数不能正常用的问题
export function ts(key: string, arg: object) {
  const {tm,locale} = useI18n()
  let _text = tm(key);
  let reg;
  for(let LKey in arg){
    reg = new RegExp('\{\\s*?'+LKey+'\\s*?\}','g');
    // @ts-ignore
    _text = _text.replace(reg, arg[LKey])
  }
  return _text;
}

// 使用:ts('test', {key1: 'key1Val', key2: 'key2Val'})

解决方案2:

方案来源:

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

shell 复制代码
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

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.

解决方案:

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

其他相关文献:

相关推荐
llz_1128 分钟前
web-第二次课后作业
前端·后端·web
vipbic5 小时前
别再把“做个H5”挂嘴边了:这个词,官方压根就没有定义过
前端
剑神一笑6 小时前
Linux pgrep 命令详解:按名称查找进程 PID 的高效方法
linux·运维·chrome
剑神一笑6 小时前
Linux killall 命令详解:按进程名批量终止进程的原理与实践
linux·运维·chrome
ZC跨境爬虫7 小时前
跟着 MDN 学CSS day_39:(Flexbox 弹性盒子核心机制)
前端·css·ui·html·tensorflow
小陈同学呦7 小时前
前端如何处理订单状态导航的数据竞态问题
前端·javascript
喵个咪7 小时前
GoWind Toolkit 前端代码生成|Vue3(ElementPlus/Vben)、React(AntDesign)全自动一键生成教程
前端·vue.js·react.js
qq_2518364579 小时前
SpringBoot+Vue 共享电池柜管理系统 完整实现 前后端分离项目实战 完整代码
vue.js·spring boot·后端
摆烂大大王9 小时前
玩转 OpenClaw:用 TaskFlow + Heartbeat 打造自动化工作流
前端·人工智能·自动化
zhangxingchao9 小时前
AI 大模型核心六:量化、Workflow 与 Agent、多轮 RAG
前端·人工智能·后端