I am trying to get started using i18next with an Express server, but cannot get it working based on the examples in the docs.
My app consists of index.js (my Express server), package.json, and a locales directory with two translation files: en.json and 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"
}
}
locales/en.json
{
"home": {
"title": "Hello World!"
}
}
locales/es.json
{
"home": {
"title": "Hola Mundo!"
}
}
via Shaun Scovil
No comments:
Post a Comment