【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'
  },
},

其他相关文献:

相关推荐
发现一只大呆瓜2 小时前
深度解密 Rollup 插件开发:核心钩子函数全生命周期图鉴
前端·vite
java_nn2 小时前
一文了解前端技术
前端
发现一只大呆瓜2 小时前
深度解析 Rollup 配置与 Vite 生产构建流程
前端·vite
小码哥_常3 小时前
安卓黑科技:让手机成为你的“跌倒保镖”
前端
小李子呢02114 小时前
前端八股Vue---Vue2和Vue3的区别,set up的用法
前端·javascript·vue.js
m0_647057964 小时前
Harness Engineering 实践指南
前端
邂逅星河浪漫4 小时前
【银行内网开发-管理端】Vue管理端+Auth后台开发+Nginx配置+Linux部署(详细解析)
linux·javascript·css·vue.js·nginx·html·前后端联调
JJay.4 小时前
Android BLE 稳定连接的关键,不是扫描,而是 GATT 操作队列
android·服务器·前端
一 乐4 小时前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·电影院购票管理管理系统
星空椰4 小时前
JavaScript 进阶基础:函数、作用域与常用技巧总结
开发语言·前端·javascript