你如何配置i18next-express-middleware?

时间:2017-05-15 17:54:52

标签: node.js express middleware i18next

我正在尝试开始在Express服务器上使用i18next,但根据文档中的示例无法使其工作。

我的应用程序包含index.js(我的Express服务器),package.json和带有两个翻译文件的locales目录:en.json和es.json。

index.js

'use strict';

const express = require('express');
const i18n = require('i18next');
const i18nMiddleware = require('i18next-express-middleware');
const path = require('path');

const app = express();
const port = process.env.PORT || 8080;

i18n
  .use(i18nMiddleware.LanguageDetector)
  .init({
    fallbackLng: 'en',
    lowerCaseLng: true,
    preload: ['en', 'es'],
    resGetPath: path.join(__dirname, 'locales/__lng__.json'),
    useCookie: false
  });

app.use(i18nMiddleware.handle(i18n, {
  removeLngFromUrl: false
}));

app.get('/', (req, res) => {
  res.send(req.t('home.title'));
});

app.use(express.static(path.join(__dirname, 'public')));

module.exports = app.listen(port, (err) => {
  if (err) {
    console.log(err);
    process.exit(1);
  } else {
    console.log(`Server is listening on port ${port}`);
  }
});

的package.json

{
  "name": "i18n-server",
  "version": "1.0.0",
  "description": "Node Express server with i18next.",
  "main": "index.js",
  "scripts": {
    "start": "node index.js"
  },
  "author": "Shaun Scovil <sscovil@gmail.com>",
  "license": "ISC",
  "dependencies": {
    "express": "4.15.2",
    "i18next": "8.2.1",
    "i18next-express-middleware": "1.0.5"
  }
}

区域设置/ en.json

{
  "home": {
    "title": "Hello World!"
  }
}

区域设置/ es.json

{
  "home": {
    "title": "Hola Mundo!"
  }
}

1 个答案:

答案 0 :(得分:3)

看起来像一个非常古老的配置...跟随自述后端被移动到自己的插件...你的代码应该类似于:

var i18next = require('i18next');
var FsBackend = require('i18next-node-fs-backend');
var middleware = require('i18next-express-middleware');
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');

i18next
  .use(FsBackend)
  .init({
    lng: 'en',
    saveMissing: true,
    debug: true,
    backend: {
      loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json',
      addPath: __dirname + '/locales/{{lng}}/{{ns}}.missing.json'
    },
    nsSeparator: '#||#',
    keySeparator: '#|#'
  });

var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

app.use(middleware.handle(i18next, {
  // ignoreRoutes: ["/foo"],
  // removeLngFromUrl: false
}));

作为示例,您可以查看https://github.com/i18next/i18nextify/blob/master/example/server.js

并且对于文件系统,请查看https://github.com/i18next/i18next-node-fs-backend以获取详细信息