i18next - Loading translations from a JSON file - node.js

I'm trying to load translations from a JSON file using i18next library on Node. The path of the JSON file points to the correct location.
I'm getting the following error:
i18next::translator: missingKey en translation test test
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});
JSON file:
{
"foo": "bar"
}
Specifying the translations directly in createInstance using resources property works perfectly.
I tried everything I could think of, with no success.

Found the solution!
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const instance = i18next.use(Backend).createInstance();
instance.init({
lng: config.language,
debug: true,
fallbackLng: 'en',
initImmediate: false,
backend: {
loadPath: join(__dirname, `${config.language}.json`),
},
}, (error, t) => {
console.log(t('foo'));
});

Related

Jest+NextJs: You should only use "next/router" on the client side of your app

I'm mocking the next/router dependency in my Jest+React-testing-libray tests as I always have:
import * as nextRouter from 'next/router';
export const routerData = {
pathname: '/users/create',
route: '/users/create',
query: { },
asPath: '/users/create',
isFallback: false,
basePath: '',
isReady: true,
isPreview: false,
isLocaleDomain: false,
events: {},
};
// mock router
jest.mock('next/router');
nextRouter.useRouter.mockImplementation(() => (routerData));
describe('a component that requires next/router, () => ... );
This had been working correctly but after updating to NextJs 12.2.0 I get this warning:
No router instance found.
You should only use "next/router" on the client side of your app.
This warning makes all my tests with the mocked router to fail.
Ideas to fix this?
Well, it appears that this is not related to 12.2.0. Somehow my last version of Next - 12.0.0 - wasn't thrownig this error but other older versions did.
Thanks to bistacos for the response here.
const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
pathname: '/',
...moreRouterData
}));

NodeJS email-templates i18n localization

I have an issue with the localization of the pug templates combined with i18n. The language keeps rolling back to "en" language, but I've set the locale: 'sl' in the send() function, this is from the documentation of the email-templates.
Here is my code in typescript:
import * as path from 'path';
import Email = require("email-templates");
import { transporter } from '../mailerConnection';
import { I18n } from 'i18n';
export async function sendOutActivationEmail() {
const i18n = new I18n();
i18n.configure({
locales: ['en', 'sl'],
directory: path.join(__dirname, '../../locales'),
register: global
});
const email = new Email({
message: {
from: '"test" <noreplay#test.com>'
},
// uncomment below to send emails in development/test env:
//send: true,
transport: transporter,
i18n: i18n
});
email
.send({
template: path.join(__dirname, '../templates', 'activation'),
message: {
to: 'test#gmail.com'
},
locals: {
locale: 'sl',
name: 'Test'
}
})
.then(console.log)
.catch(console.error);
}
sendOutActivationEmail().catch(console.error);
Here is html.pug template:
p= __('message')
Here is en.json:
{
"message": "message1"
}
Here is sl.json:
{
"message": "messageSLO"
}
Here is the link to email-templates localization documentation: https://www.npmjs.com/package/email-templates#localization
What am I doing wrong that the functions doesn't switch to "sl" language? Thanks...
email-templates does not seem to document how the i18n object needs to look like, but probably you need to pass there somewhere the appropriate translations…
Alternatively, this looks more promising: https://dev.to/adrai/how-does-server-side-internationalization-i18n-look-like-5f4c#email
Actually they use extension of the default i18n package is ladjs/i18n so the object that you pass to the email-template needs to be in different shape.
I solved my issue using the code below:
const email = new Email({
message: {
from: '"Test" <noreplay#test.com>'
},
// uncomment below to send emails in development/test env:
//send: true,
transport: transporter,
i18n: {
locales: ['en', 'sl'],
directory: path.join(__dirname, '../../locales'),
defaultLocale: 'en'
}
});

Vue Website Returns "Cannot Get /path" On All Pages EXCEPT Index

I am using Vue on Node.js to host my website on an AWS EC2 instance. I dont have an index node.js file, just the vue-router file. I use AWS CloudFront to bind my certificate to my traffic. The problem is that everytime i access the site through the server's link, the site works perfectly, but whenever i access it through the cloud-front link, only the index of the website will show up. No /about or /contact; instead it returns Cannot GET /about.
My Router:
import Vue from 'vue';
import Router from 'vue-router';
import VueCookies from 'vue-cookies';
import Home from './views/Home.vue';
import NotFound from './views/NotFound.vue';
Vue.use(Router);
Vue.use(VueCookies);
VueCookies.config('7d');
VueCookies.set('theme', 'default');
VueCookies.set('unique', Date.now());
VueCookies.set('rwapi-uuid', `v3-${Date.now()}-x9k0`)
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'INDEX', component: Home },
{ path: '/about/', name: 'ABOUT', component() { return import('./views/About.vue'); } },
{ path: '/portfolio', name: 'PORTFOLIO', component() { return import('./views/Port.vue'); } },
{ path: '/contact', name: 'CONTACT', component() { return import('./views/Contact.vue'); } },
{ path: '/login', name: 'LOGIN', component() { return import('./views/Login.vue'); } },
{ path: '/404', component: NotFound },
{ path: '*', redirect: '/404' },
],
});
I have already tried to add the historyApiFallback: true to my webpack config but it had no effect.
According to Vue Router's documentation, when using your router in history mode, your webserver requires additional configuration.
I don't exactly know how do EC2 instances work, but if you don't have a webserver proxying all your requests to index.html, Vue-router will not be able to handle the other requests.

How to structure a Vue 2.0 app for server-rendered lazy routes?

I attempted to modify vue-hackernews-2.0 to support lazy-loaded routes using Webpack's code-splitting feature as per instructions found at these links:
https://router.vuejs.org/en/advanced/lazy-loading.html
http://vuejs.org/guide/components.html#Async-Components
However, I ran into some issues. When I loaded the app in the browser, all suggested variations of syntax triggered Module not found errors on the server-side when attempting to load in the server-side chunks.
Given this wrapper around the code-split points in router.js...
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
// INSERT CODE-SPLIT POINT SYNTAXES HERE (they are below)
export default new Router({
mode: 'history',
routes: [{
path: '/',
component: Home
}, {
path: '/foo',
component: Foo
}]
})
All of these variations of syntax threw the Module not found error:
Variation 1:
const Home = () => System.import('./views/Home.vue')
const Foo = () => System.import('./views/Foo.vue')
Variation 2:
const Home = (resolve) => require(['./views/Home.vue'], resolve)
const Foo = (resolve) => require(['./views/Foo.vue'], resolve)
Variation 3:
const Home = (resolve) => {
require.ensure(['./views/Home.vue'], () => {
resolve(require('./views/Home.vue'))
})
}
const Foo = (resolve) => {
require.ensure(['./views/Foo.vue'], () => {
resolve(require('./views/Foo.vue'))
})
}
The error message was always along the lines of:
(note: this error is adapted from a small reproduction I made of the issue, not from the hackernews example)
Error: Cannot find module './0.server.js'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Function.requireEnsure [as e] (__vue_ssr_bundle__:42:25)
at Home (__vue_ssr_bundle__:152:30)
at /Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1421:19
at iterator (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1277:5)
at step (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1213:9)
at step (/Users/razorbeard/projects/vue-2-ssr/node_modules/vue-router/dist/vue-router.js:1217:9)
I tried adapting my code to use the suggestions offered at Server-side react with webpack 2 System.import, but those did not work either.
I read a post that described configuring a build-time global variable using Webpack's DefinePlugin that allowed me to inspect whether the code was running on the server or on the client - this allows me to code-split on the client, but just bundle everything in on the server.
In the server webpack config:
{
...
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: false
})
]
...
}
In the client webpack config:
{
...
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: true
})
]
...
}
Then, in the same wrapper-snippet as above for the router.js file, I used this variation of syntax:
const Home = BROWSER_BUILD ? () => System.import('./views/Home.vue') : require('./views/Home.vue')
const Foo = BROWSER_BUILD ? () => System.import('./views/Foo.vue') : require('./views/Foo.vue')
This made rendering work - partially. Navigating directly to the app in the browser (and respective routes) server-rendered the correct UI. Clicking around, vue-router's client-side logic took me to the right UI. Everything seemed hunky-dory - until I opened DevTools:
The same issue also occurs if a module is loaded lazily as a subcomponent of a route:
<template>
<div class="page">
<heading></heading>
</div>
</template>
<script>
const Heading = BROWSER_BUILD ? () => System.import('./Heading.vue') : require('./Heading.vue')
export default {
components: {
Heading
}
}
</script>
I tried asking for some help in the official Vue forum, but came up empty: http://forum.vuejs.org/t/2-0-help-needed-with-server-rendered-lazy-routes/906
Thinking this might be a bug with vue-router, I opened an issue there: https://github.com/vuejs/vue-router/issues/820
Unfortunately, I wasn't able to find a solution.
So, I put together a small repo that reproduces the issue: https://github.com/declandewet/vue2-ssr-lazy-error
I have a hunch that the actual problem might be coming from https://www.npmjs.com/package/vue-server-renderer.
I'm really stuck on this and am used to how easy it is to do in react - and would really appreciate any help/tips/direction towards a solution!
Here is the webpack config from the reproduction repo for convenience:
import fs from 'fs'
import path from 'path'
import webpack from 'webpack'
import validate from 'webpack2-validator'
import { dependencies } from './package.json'
let babelConfig = JSON.parse(fs.readFileSync('./.babelrc'))
/* turn off modules in es2015 preset to enable tree-shaking
(this is on in babelrc because setting it otherwise causes issues with
this config file) */
babelConfig.presets = babelConfig.presets.map(
(preset) => preset === 'es2015' ? ['es2015', { modules: false }] : preset
)
const babelOpts = {
...babelConfig,
babelrc: false,
cacheDirectory: 'babel_cache'
}
const SHARED_CONFIG = {
devtool: 'source-map',
module: {
loaders: [{
test: /\.vue$/,
loader: 'vue'
}, {
test: /\.js$/,
loader: 'babel',
exclude: 'node_modules',
query: babelOpts
}]
},
resolve: {
modules: [
path.join(__dirname, './src'),
'node_modules'
]
}
}
const SERVER_CONFIG = validate({
...SHARED_CONFIG,
target: 'node',
entry: {
server: './src/server.js',
renderer: './src/renderer.js'
},
output: {
path: path.join(__dirname, './dist'),
filename: '[name].js',
chunkFilename: '[id].server.js',
libraryTarget: 'commonjs2'
},
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: false,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.BannerPlugin({
banner: 'require("source-map-support").install();',
raw: true,
entryOnly: false
})
],
externals: Object.keys(dependencies)
})
const CLIENT_CONFIG = validate({
...SHARED_CONFIG,
entry: {
app: './src/client.js',
vendor: ['vue']
},
output: {
path: path.join(__dirname, './dist/assets'),
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin({
BROWSER_BUILD: true,
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'vendor.js'
})
]
})
export default [SERVER_CONFIG, CLIENT_CONFIG]
EDIT: Noticing that in React, we use match on the client to get the right route config for the current view, I decided to inspect what components were getting matched using app.$router.getMatchedComponents() and found something interesting:
Server Entry:
import app from './app'
export default (context) => {
// using app.$router instead of importing router itself works
// (not sure why the hacker-news example imports the router module instead...)
app.$router.push(context.url)
const components = app.$router.getMatchedComponents()
console.log('server-side', components)
return Promise.all(components.map((component) => component))
.then(() => app)
}
When navigating to the home page, this logs to the terminal:
server-side [ { __file: '/Users/razorbeard/projects/vue-2-ssr/src/views/Home.vue',
render: [Function],
staticRenderFns: [ [Function] ] } ]
Client Entry:
import app from './app'
const components = app.$router.getMatchedComponents()
console.log('client-side', components)
// kickoff client-side hydration
Promise.all(components.map((component) => Promise.resolve(component)))
.then(() => app.$mount('#app'))
When navigating to the home page, this logs to the devtools console:
client-side []
As you can see, no components are getting matched on the client side.

nodejs i18next is not translating string

I have this err:authentication:invalid_token in json file. folder is setup as locales/vi_VN/mynamespace-vi_VN.json. However, it's not translating in the console.log below.
Any idea why?
i18n.init({
debug: true,
preload: ['vi_VN'],
resGetPath: 'locales/__lng__/__ns__-__lng__.json',
lng: 'en_GB',
ns: 'mynamespace',
sendMissingTo: 'fallback',
fallbackLng: 'en_GB'
}, function(err, t) {
console.log('i18n is initialized.')
console.log('Translation on:', t('err:authentication:invalid_token', {
lng: 'vi_VN'
}))
})
My bad, i was using colon : in identifier. I need to change it to something else or put it in appropriate namespace

Resources