鍍金池/ 問(wèn)答/HTML5  HTML/ koa2怎么配置國(guó)際化

koa2怎么配置國(guó)際化

我按照i18next提供的演示代碼

const i18next = require('i18next');
const i18m = require('koa-i18next-middleware');
 
// add custom detector.
i18m.LanguageDetector.addDetector({
    name: 'mySessionDetector',
 
    lookup(ctx, options) {
        let found;
        if (options.lookupSession && ctx && ctx.sessions) {
            found = ctx.sessions[options.lookupMySession];
        }
        return found;
    },
 
    cacheUserLanguage(ctx, lng, options = {}) {
        if (options.lookupMySession && ctx && ctx.session) {
            ctx.session[options.lookupMySession] = lng;
        }
    }
});
 
i18next.use(i18m.LanguageDetector).init({
    fallbackLng: 'en',
    preload: ['en', 'es'],
    resources: {
        en: {
            translation: {
                "key": "hello world"
            }
        },
        es: {
            translation: {
                "key": "es hello world es"
            }
        }
    },
    detection: {
        order: ['querystring', 'path', /*'cookie', 'header',*/ 'session', 'mySessionDetector'],
 
        lookupQuerystring: 'lng',
 
        lookupParam: 'lng', // for route like: 'path1/:lng/result'
        lookupFromPathIndex: 0,
 
        // currently using ctx.cookies
        lookupCookie: 'i18next',
        // cookieExpirationDate: new Date(), // default: +1 year
        // cookieDomain: '', // default: current domain.
 
        // currently using ctx.session
        lookupSession: 'lng',
 
        // other options
        lookupMySession: 'lang',
 
        // cache user language
        caches: ['cookie', 'mySessionDetector']
    }
}, (err, t) => {
    // initialized and ready to go!
    const hw = i18next.t('key'); // hw = 'hello world'
    console.log(hw);
});
 
app.use(i18m.getHandler(i18next, {
        locals: 'locals',
        ignoreRoutes: ['/no-lng-route'],
    })
);
 

控制臺(tái)提示出錯(cuò)

clipboard.png

這個(gè)怎么辦!

回答
編輯回答
裸橙

我也去弄了一下koa-i18next-middleware,目測(cè)下來(lái)是這個(gè)庫(kù)的問(wèn)題,已經(jīng)有人提了issue,庫(kù)主還沒(méi)有修復(fù),你可以換成試試koa官方的i18n以及locales。

2018年3月11日 13:30