vite + vue-i18n利用時のglobalInjectionについて
vite で vue-i18n を利用する際に、グローバルオブジェクトが参照できない場合があります。
npm run dev (vite)の場合は、起動時にエラーは出ませんが、i18nを使っている画面を開くと
Uncaught ReferenceError: global is not defined
npm run build(vite build)の場合は、esbuild実行時にエラーが出ます。
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
^
});
}
工夫が必要・・・
対処法で、vite.config.jsのdefine
に、globalを追加するなど出て来ますが、他のプラグインをビルドする際に、問題になるので工夫が必要でした。
vite.config.js
define: {
global: "window", // これはよろしく無い
__VUE_I18N_FULL_INSTALL__: true,
},
私の場合は、element-plusを使おうとした際に、ビルド時に用意されていない設定を解決しに行ってしまいました。
Could not resolve "./components/config-provider/src/hooks/use-window-config.mjs" from "node_modules/element-plus/es/index.mjs"
file: /Users/sameshima/freestyle/axisnet/axisnet-web/node_modules/element-plus/es/index.mjs
error during build:
RollupError: Could not resolve "./components/config-provider/src/hooks/use-window-config.mjs" from "node_modules/element-plus/es/index.mjs"
正解は、createI18n()のオプションで、globalInjection: true
する事でした。
globalInjectionを有効にする事で、I18nの$t()の$が効くようにします。
src/i18n.js
import { createI18n } from "vue-i18n";
import ja from "./locales/ja.json";
export default createI18n({
legacy: false,
globalInjection: true,
locale: "ja",
messages: {
ja,
},
});
さらに、、、
npm run dev (vite) の場合は、 NODE_ENVがdevelopment
npm run build(vite build)の場合は、NODE_ENVがproduction
となるのを利用して、defineセクションに、globalを初期化するかどうかを切り替えました。
vite.config.js
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { fileURLToPath } from "url";
import Icons from "unplugin-icons/vite";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
const config = {
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
Icons({
autoInstall: true,
}),
],
resolve: {
alias: {
"@": fileURLToPath(new URL("./src", import.meta.url)),
},
},
define: {
__VUE_I18N_FULL_INSTALL__: true,
},
build: {
chunkSizeWarningLimit: 1000,
},
};
if (process.env.NODE_ENV !== "production") {
config.define.global = {};
}
// https://vitejs.dev/config/
export default defineConfig(config);
各種バージョン
node:16.20.0
package.json
"dependencies": {
"@element-plus/icons-vue": "^2.1.0",
"@formkit/icons": "latest",
"@formkit/pro": "latest",
"@formkit/vue": "latest",
"aws-amplify": "^5.2.7",
"axios": "^1.4.0",
"vue": "^3.2.47",
"vue-body-class": "^3.0.2",
"vue-i18n": "^9.2.2",
"vue-router": "^4.2.2",
"vue3-easy-data-table": "^1.5.45",
"vuex": "^4.1.0",
"vuex-persistedstate": "^4.1.0"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.1.0",
"element-plus": "^2.3.6",
"unplugin-auto-import": "^0.16.4",
"unplugin-element-plus": "^0.7.1",
"unplugin-icons": "^0.16.3",
"unplugin-vue-components": "^0.25.1",
"vite": "^4.3.9"
},
同じエラーに悩んでいらっしゃる方に、幸あらんことを!