[vue] 다국어 처리 i18n with 문자열+이미지파일명

Edward Hyun·2022년 7월 5일
0

app&web-dev

목록 보기
127/178

다국어 처리를 위해서는
문자열 뿐만 아니라 한글이 들어가는 이미지 파일을 처리해야 할 필요가 있다.
이미지 내 문자를 변역해서 나오는 이미지 파일들을 구분하기 위해
각 파일 명을 동일하게 가고 끝에 _ko 같이 구분자를 붙여준다.

하지만 파일명을 인식하지 못하기 때문에
각 파일명을 문자열로 따로 저장한다.

다국어 문자열 처리를 위해
en.json ko.json 같이 json 파일을 만들고
"키워드" : "내용"으로 쌍으로 값을 넣는다.
여기에 이미지 파일명도 "키워드" : "내용" 쌍으로 넣어
같은 json 파일에 두면

다국어 문자열 처리처럼 파일명을 관리하고
이미지를 호출할 때 해당 파일명으로 이미지를 로딩처리한다.

즉, 다음과 같다.

ko.json 
{
	"message": {
		"hello": "안녕"
    },
    "image": {
	    "image1": "image1_ko.png"
    }
}

en.json 
{
	"message": {
    	"hello": "Hi, there"
	},
    "image": {
        "image1": "image1_en.png"
	}
}

참고 :
https://blog.naver.com/dalsae1995/222736888695 (good)
https://vue-i18n.intlify.dev/guide/advanced/composition.html (composition api)
https://codesandbox.io/s/zdmjy
https://vue-i18n.intlify.dev/
https://dong-queue.tistory.com/64

(중요!!!)
composition api를 사용하는 경우에는 legacy: false를 정해 줘야 한다. global하게 사용하기 위해 globalInjection: true까지 준다.

const i18n = VueI18n.createI18n({
  legacy: false, // you must set `false`, to use Composition API
  locale: 'ja', // set locale
  fallbackLocale: 'en', // set fallback locale
  globalInjection: true,
  messages, // set locale messages
  // If you need to specify other options, you can set other options
  // ...
})

아래 에러를 안내기 위해 아래 사항에 유념하자!
Uncaught SyntaxError: Must be called at the top of a setup function

(중요!!!)

// features/utils.js

//import { useI18n } from 'vue-i18n'
//const { t } = useI18n() // Uncaught SyntaxError: Must be called at the top of a `setup` function

import i18n from '../i18n'

const { t } = i18n.global

https://stackoverflow.com/questions/57049471/problem-to-use-vuei18n-outside-a-component

From vue-i18n v9, you need to use global of I18n instance that is created createI18n
API docs here:
https://vue-i18n.intlify.dev/api/general.html#global

In about example, I think lazy-loading example will be helped for you:
https://github.com/intlify/vue-i18n-next/blob/master/examples/lazy-loading/vite/src/i18n.ts

(locale 변경하기)
composition api인 경우,

i18n.global.locale.value = 'en'

이렇게 넣어야 한다.
https://vue-i18n.intlify.dev/guide/essentials/scope.html#locale-changing

(중요!!!) 이미지 파일명 처리하기

<img :src="require(`@assets/images/${t('image.image1')}`)">

require를 사용하여 동적으로 불러올 때 t함수로 다국어 처리된 파일명을 불러온다.

이미지파일 처리 관련 :: img-src, css-background)
https://im-designloper.tistory.com/81

그외에 동적으로 이미지를 불러오고 싶은 때는 import를 setup 안에서 호출하려면

const imagefile1 = (await import(`@assets/images/${t('image.image1')}`)).default;

과 같이 불러올 수 있다. 이는 import 모듈 동적처리와 관계된 내용.(https://ko.javascript.info/modules-dynamic-imports)

profile
앱&웹개발(flutter, vuejs, typescript, react), 인공지능(nlp, asr, rl), 백엔드(nodejs, flask, golang, grpc, webrtc, aws, msa, nft, spring cloud, nest.js), 함수형 프로그래밍(scala, erlang)을 공부하며 정리합니다.

0개의 댓글