Laravel+Vue3 i18n报错:en语言包未找到'message'键求助
问题解决:Laravel + Vue3 i18n 语言包键缺失
核心问题定位
控制台警告[intlify] Not found 'message' key in 'en' locale messages.的原因是JSON文件导入方式错误:Laravel Mix(基于Webpack)导入JSON文件时,直接返回文件内容对象,而非带有default属性的模块。你当前代码中locales(key).default会获取到undefined,导致语言包未正确加载。
修复步骤
- 修改
resources/js/i18n.js中的加载逻辑
将messages[locale] = locales(key).default;改为直接赋值导入的JSON内容:
import { createI18n, LocaleMessages, VueMessageType } from "vue-i18n"; function loadLocaleMessages() { const locales = require.context( "./locales", true, /[A-Za-z0-9-_,\s]+\.json$/i ); const messages = {}; locales.keys().forEach((key) => { const matched = key.match(/([A-Za-z0-9-_]+)\./i); if (matched && matched.length > 1) { const locale = matched[1]; // 移除多余的.default,直接赋值JSON内容 messages[locale] = locales(key); } }); return messages; } export default createI18n({ legacy: false, globalInjection: true, locale: 'en', fallbackLocale: 'fr', formatFallbackMessages: true, messages: loadLocaleMessages(), });
- 验证文件结构与内容
确保resources/js/locales/en.json存在且内容正确:
{ "message": "hello i18n !!" }
- 重新编译资源
运行Laravel Mix编译命令:
npm run dev # 开发环境,或npm run production用于生产环境
完成后页面应正常显示hello i18n !!。
Laravel + Vue3 多语言实现的其他方案
方案1:复用Laravel原生本地化系统
通过API将Laravel后端的语言包传递给Vue,实现前后端语言包统一维护:
- 在Laravel的
resources/lang目录下创建语言文件(如en/messages.php) - 添加API路由返回翻译内容:
Route::get('/api/lang/{locale}', function ($locale) { app()->setLocale($locale); return response()->json(trans('messages')); });
- Vue中通过axios动态加载语言包:
import { createI18n } from 'vue-i18n'; import axios from 'axios'; const i18n = createI18n({ legacy: false, globalInjection: true, locale: 'en', fallbackLocale: 'fr', }); // 初始化加载语言包 axios.get('/api/lang/en').then(res => { i18n.global.setLocaleMessage('en', res.data); }); export default i18n;
方案2:使用Vue3组合式API风格的i18n
针对使用Composition API的组件,直接通过useI18n钩子调用翻译,替代全局$t:
<template> <h1>{{ t('message') }}</h1> </template> <script setup> import { useI18n } from 'vue-i18n'; const { t } = useI18n(); </script>
方案3:升级到Vite替代Laravel Mix
Laravel 9+默认支持Vite,Vite对ES模块的支持更友好,搭配@intlify/unplugin-vue-i18n插件可简化语言包配置:
- 修改
vite.config.js添加插件:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import vue from '@vitejs/plugin-vue'; import vueI18n from '@intlify/unplugin-vue-i18n/vite'; import path from 'path'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.js'], refresh: true, }), vue(), vueI18n({ include: path.resolve(__dirname, './resources/js/locales/**'), }), ], });
- 简化
i18n.js直接导入语言文件:
import { createI18n } from 'vue-i18n'; import en from './locales/en.json'; import fr from './locales/fr.json'; export default createI18n({ legacy: false, globalInjection: true, locale: 'en', fallbackLocale: 'fr', messages: { en, fr }, });
内容的提问来源于stack exchange,提问作者abdallah al sawaqi
相关产品推荐
相关产品推荐

