IT/Nuxt & vue

[Nuxt] 구글시트(google sheet)를 이용한 다국어(i18n) 자동화 처리

2023. 1. 30. 17:58
오늘의 명언

“ 좋은 프로그래머 대부분은 돈이나 대중에게 받을 찬사를 기대하고 프로그래밍을 하지 않고 프로그래밍이 재미 있어서 한다. ”

- 리누스 토르발스 (Linus Torvalds)
목차
  1. 🔑   개요
  2. 🔑   nuxt-i18n
  3. 🔑   nuxt-google-sheets-parser
300x250

🔑   개요

 

국제화를 고려한 웹 애플리케이션을 구현하기 위해, 국제화 처리 모듈을 사용하여 구현한 예시를 입니다.

기본적인 nuxt-i18n 모듈만 사용한 방법과 public-google-sheets-parser 라이브러리를 기반으로 한 nuxt-google-sheets-parser 모듈을 사용하여 자동화 처리한 방법을 설명합니다.

 


 

🔑   nuxt-i18n

 

참고문서) nuxt-i18n

 

Introduction

i18n (Internationalization) for your Nuxt project

i18n.nuxtjs.org

 

1. package install


    
npm install @nuxtjs/i18n

 

 

2. nuxt.config.js 설정


    
modules: [
[
'@nuxtjs/i18n',
{
// 대응할 언어들 셋팅
// 관련 옵션은 문서 참조
locales: [
{ code: 'ko', iso: 'ko_KR', file: 'ko/index.js' },
{ code: 'en', iso: 'en-US', file: 'en/index.js' },
],
defaultLocale: 'ko',
langDir: 'locales/',
strategy: 'prefix_except_default',
vueI18n: {
fallbackLocale: 'ko',
messages: {
ko: ko,
en: en,
},
},
lazy: false,
vueI18nLoader: true,
vuex: false,
detectBrowserLanguage: {
useCookie: true,
cookieKey: "i18n",
},
},
],
],

 

3. 폴더 셋팅 및 언어별로 정리


    
// ko/index.js
export default {
header:{
service:'서비스',
menu:'메뉴',
button:'버튼',
login:'로그인'
}
}
// en/index.js
export default {
header:{
service:'service',
menu:'menu',
button:'button',
login:'login'
}

 

4. 구현 - > 다국어 확인


    
<template>
// 다국어 적용되었는지 확인
// ko: 서비스 , en: service
<div>
{{ $t(header.service)}}
</div>
</template>

 

 

 


 

 

🔑   nuxt-google-sheets-parser

참조문서) nuxt-google-sheets-parser

참고블로그) 블로그

 

nuxt-google-sheets-parser

public google sheets parser for nuxt.js. Latest version: 1.2.4, last published: 2 years ago. Start using nuxt-google-sheets-parser in your project by running `npm i nuxt-google-sheets-parser`. There are 2 other projects in the npm registry using nuxt-googl

www.npmjs.com

 

1.package install


    
npm install nuxt-google-sheets-parser

 

2. nuxt.config.js 설정


    
modules: [
[
'@nuxtjs/i18n',
{
// ...생략
},
// 위에 nuxt-i18n 모듈 설정 이후에 등록되어야합니다.
"nuxt-google-sheets-parser",
],
],

 

3. 구글 시트 준비

참고시트) Nuxt 국제화 구글 관리시트

ko en ja key key1 key2 ... key10
제목 title タイトル common.title common title    
내용 Contents 内容 common.description common description    

 

en, ja 필드값  GOOGLETRANSLATE 함수를 사용하여 구글에서 번역된 값을 사용하도록 했습니다.

추후 실제 번역된 텍스트가 나오기 전까지 테스트용으로 사용하면 됩니다.

 

ex) GOOGLETRANSLATE($A1, $A$1, B$1)

 

 

4. default json 파일 생성

 

구글 시트 API에서 장애가 일어났을 때, 텍스트가 깨질 수 있는 단점이 있습니다. 이를 방지하여 사전에 구글시트 기반으로 locals별 json 파일을 생성하는 소스를 구현해 봅니다.

 


    
// makeSheetData.js
const fs = require('fs')
const _ = require('lodash')
const PublicGoogleSheetsParser = require('public-google-sheets-parser')
const parser = new PublicGoogleSheetsParser()
// https://docs.google.com/spreadsheets/d/<key값>/
const sheetId = '위 시트 URL key값'
//구글 시트 이름
const sheetName = 'value1'
//언어 추가시 작성필요
const Languages = ['ko', 'en']
parser.parse(sheetId, sheetName).then((rows) => {
const dictionary = {}
rows.forEach((row) => Languages.forEach((lang) => _.set(dictionary, `${lang}.${row.key}`, row[lang])))
// 필요한 언어들에 대한 default.json 파일을 생성합니다.
Languages.forEach((lang) => fs.writeFileSync(`./locales/${lang}/default.json`, JSON.stringify(dictionary[lang])))
})

 

default.json 파일을 생성합니다.


    
node makeSheetData

 

 

5. 구글 시트 데이터 세팅

 

구글 시트데이터 결과를 저장할 파일을 locale/${locale}/index.js 경로 안에 작성합니다.

구글 시트 API가 에러가 날 경우 위에 만들어준 default.json으로 연결해 줍니다.

※ 만약 구글시트 페이지별로 모듈화가 필요하다면 각 "sheetName"으로 조회해서 dictionary에 합치면 됩니다.


    
// locals/base.js
import set from 'lodash/set'
export default async (context, locale) => {
// https://docs.google.com/spreadsheets/d/<key값>/
const sheetId = '위 시트 URL key값'
const sheetName = 'value1'
const dictionary = {}
const response = await context.$gsparser.parse(sheetId, sheetName)
if(response.length<0){
// google api가 비정상 연결일때는 미리 만들어둔 default.json data를 사용한다.
const defaultDictionary = require(`./${locale}/default.json`);
Object.assign(dictionary, defaultDictionary);
}
response.forEach((item) => set(dictionary, item.key, item[locale]));
return Promise.resolve(dictionary)
}

 

언어별로 파일을 작성합니다.


    
// locale/ko/index.js
import base from '../base'
export default (context) => {
return base(context, 'ko')
}

 

이후 콘솔로 dictionary에 잘 담겼는지 확인해보거나, 위에 i18n 사용할때 방법으로 확인하시면됩니다.

 

 

 

❗주의

 구글시트 값이 조회가 안된다면

공유 버튼 클릭 후 "일반 엑세스" 를 확인하시면됩니다.

 


 

 

i18n방식으로만 하는 방법과 구글시트로 동적으로 json파일을 가져와 처리하는 방법 두 가지를 해보았는데요.

참고한 블로그 내용을 토대로 한번 정리해 봤습니다. 국제화 작업이 필요한 웹 사이트에서 다양하게 적용해 볼 수 있을 거 같아서 많은 도움이 되었습니다. 물론 다른 방식과 구현방법이 있겠지만 조금이라도 도움이 되었으면 합니다.!

 

 

 

 

반응형
저작자표시 비영리 변경금지 (새창열림)
잘못된 내용이 있으면 댓글 부탁드립니다. 감사합니다.
Stack_Shines
Stack_Shines
프론트엔드 백엔드 학습정리 및 정보공유 블로그입니다.
'IT/Nuxt & vue' 카테고리의 다른 글
  • [Nuxt] Axios interceptors 사용하기
  • [Nuxt] Axios 와 Proxy 사용 방법 (CORS)
  • [Nuxt] 구글 로그인
  • [Nuxt] 카카오 로그인 Nuxt 설정 및 카카오 정보 발급 - ②(END)
느린 개발자프론트엔드 백엔드 학습정리 및 정보공유 블로그입니다.
Stack_Shines
느린 개발자
Stack_Shines
전체
오늘
어제
  • 분류 전체보기 102
    • 티스토리 10
    • IT 67
      • Library 3
      • JavaScript 3
      • TypeScript 3
      • Nuxt & vue 14
      • Nuxt3 6
      • React 4
      • NestJS 4
      • Express 9
      • CI CD 1
      • WebGl 4
      • docker 6
      • MAC 2
      • 디자인패턴 1
      • Error 4
      • 홈서버 3
    • 프로젝트 1
    • 오늘의 회고 2
    • 맛리뷰 7
    • 다이어트 5
    • 여행 1
    • 끄적끄적 일상 6
    • 생활 정보 3

인기 글

최근 글

hELLO · Designed By 정상우.
Stack_Shines
[Nuxt] 구글시트(google sheet)를 이용한 다국어(i18n) 자동화 처리
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.