Get translation text without using FormattedMessage and React ContextTypes - node.js

I'm looking for a way to get translation text without using FormattedMessage. Until now, I've found only this solution that provides to use ContextTypes an React's EXPERIMENTAL feature. Are there others ways to accomplish this (or other library/npm module)?

I prefer using context, but react-intl does also provide a higher order component injectIntl you can use instead. This will pass a prop intl that has all the imperative formatting functions.
import React from "react";
import {injectIntl, intlShape} from "react-intl";
class MyComponent extends React.Component {
static propTypes = {
intl: intlShape.isRequired
}
render() {
return <p>{this.props.intl.formatDate(new Date())}</p>;
}
}
export default injectIntl(Component);

Related

How to use any of i18n packages in nestjs mvc?

I found this package nest-18n but that dudes thinks that nestjs is only used for api and not mvc.
So sure ?lang=en or ?lang=de works and it changes language but question is how to use that on view?
My first thought was that this is working out of the box with __("Something to translate"). But that will not work (__ is undefined).
Since i18Service.translate method is async you can not add it to view (there is pug then but that is horrible idea). Idea of adding anything on the the view that is async does not make sense at all. So in principle they made package that can not be used outside of api's.
Other thing that i can do is to have something like
class AppController extends BaseController() {
#Get("/")
index() {
return {
someTranslation: await this.getTranslation("give me something to translate"),
// IMAGINE NOW Having 1000 OF TRANSLATION ON INDEX PAGE
}
}
}
where BaseController is:
class BaseController() {
constructor(private readonly i18n: I18nService, lang: string) {
}
async protected getTranslation(stringToTranslate: string) {
return await this.i18n(stringToTranslate, {lang});
}
}
Does anyone have idea how to use any of i18n in nestjs mvc?

Git message type on library update

I make my own react boilerplate and come until updating packages. So I've update react across major version (v15x to v16x), and change my code on a module file called injectReducer. So what i've changed in injectReducer is from this:
static contextTypes = {
store: PropTypes.object.isRequired,
};
to this:
static contextType = ReactReduxContext;
Now I think this doesn't do any breaking changes on my boilerplate, because the use of the module still the same (backward compatible). But what about the package I've updated? Should any library updated across major is considered breaking changes? What about minor updates?
Here is my full code of injectReducer:
import React from 'react';
import { ReactReduxContext } from 'react-redux';
import hoistNonReactStatics from 'hoist-non-react-statics';
import getInjectors from './reducerInjectors';
export default ({ key, reducer }) => (WrappedComponent) => {
class ReducerInjector extends React.Component {
static WrappedComponent = WrappedComponent;
static displayName = `withReducer(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`;
static contextType = ReactReduxContext;
injectors = getInjectors(this.context.store);
componentWillMount() {
const { injectReducer } = this.injectors;
injectReducer(key, reducer);
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return hoistNonReactStatics(ReducerInjector, WrappedComponent);
};
But what about the package I've updated? Should any library updated across major is considered breaking changes?
That is the idea behing the major version in semver
when you make incompatible API changes
Except I would consider it does not involve just the API.
See as an example "Semantic Versioning, Go Modules, and Databases" (just to illustrate the kind of non-API change which would still warrant a major version bump)
Basically, if any client of your library has work to do in order to adapt to the new version... your change should be considered major.
If not: minor.

Highlightjs with Angular?

The ng2-smart-table application documentation has code elements snippets that look like this:
<code highlight class="typescript">{{ snippets.require }}</code>
The resulting documentation looks like this.
When looking at the resulting application html, it looks like highlightjs is doing the highlighting, but I don't see an import of an angular dependency that would perform the transform (Or any preprocessing by the scripts), so just wondering how it works?
Per the Answer
Thought is as really cool how simple this is to do with Angular:
import { Directive, ElementRef, AfterViewInit } from '#angular/core';
import * as hljs from 'highlight.js';
#Directive({
selector: 'code[highlight]',
})
export class HighlightCodeDirective implements AfterViewInit {
constructor(private elRef: ElementRef) { }
ngAfterViewInit() {
hljs.highlightBlock(this.elRef.nativeElement);
}
}
Check the code more closely there is a highlight directive (ng2-smart-table/src/app/shared/directives/highlight.directive.ts) that uses highlightjs. It is part of the sample application not the library so you need to copy it if you want to do the same in your application.

how to call class without declaring it in constructor angular 2

I am trying to use NFC module of Ionic 2. This is my code:
nfc-scan.ts:
import {Component} from '#angular/core';
import {IonicPage, NavController, NavParams, Platform} from 'ionic-angular';
import { Device } from '#ionic-native/device';
import {NFC, Ndef} from '#ionic-native/nfc';
#IonicPage()
#Component({
selector: 'nfc-scan',
templateUrl: 'nfc-scan.html',
})
export class NfcScan {
#ViewChild(Nav) nav: Nav;
NFC: NFC;
constructor(public platform: Platform,
public navCtrl: NavController,
public navParams: NavParams,
) {
}
// NFC Scanning
checkNFC()
{
this.NFC.enabled()
.then(() => {
this.addListenNFC();
})
.catch(err => {
console.log(err);
});
}
}
nfs-scan.html
<ion-content padding>
<button on (click)="checkNFC()">Scan NFC</button>
</ion-content>
When I run the application, I get the error:
Property 'enabled' does not exist on type 'typeof NFC'.
I know I am not declaring NFC in the constructor of nfc-scan.ts. But when I do so, the page won't even load altogether.
I did finally manage to find a solution to this problem. It turns out that it's true you can't use a class without declaring it in the constructor of the class where you want to use it.
In my case, the issue was, that I was running the app in my machine's (Macbook) browser, whereas NFC plugin can only be instantiated on a phone that supports NFC (Like camera plugin). Having said that, Ionic now provides ability to mock plugins in a way so that you can use them in your machine's browser.
To use an Ionic Native plugin in the browser and ionic serve session,
you just need to extend the original plugin class and override the
methods you’d like to mock.
Source: https://ionicframework.com/docs/native/browser.html
Hope it helps someone like me.
You would usually see an output on the console, when the page is not loading. Make sure to use private nfc : NFC in the constructor;

Typescript IOC in case of node

I am wondering how would you use typescript IOC specifically node app.
In case of external module-based architecture there is no any classes in the app. Just pure modules because my app heavily depends on node_modules.
How would I integrate IOC solution in such case? Any thoughts?
Here is my specific case I want to use IOC for:
I have mongoose model:
interface IStuffModel extends IStuff, mongoose.Document { }
var Stuff= mongoose.model<IStuffModel>('Stuff', Schemas.stuffSchema);
export = Stuff;
And related fake class:
export class Stuff implements IStuff {
//do stuff
}
How would I integrate IOC solution in such case
Here is a very popular library that I recommend : https://github.com/inversify/InversifyJS
External modules
Using external modules doesn't change the code at all. Instead of
kernel.bind(new TypeBinding<FooBarInterface>("FooBarInterface", FooBar));
Production
You just have
import {ProdFooBar} from "./prodFooBar";
kernel.bind(new TypeBinding<FooBarInterface>("FooBarInterface", ProdFooBar));
Test
import {MockFooBar} from "./mockFooBar";
kernel.bind(new TypeBinding<FooBarInterface>("FooBarInterface", MockFooBar));
As Basarat indicated in his answer, I have developed an IoC container called InversifyJS with advanced dependency injection features like contextual bindings.
You need to follow 3 basic steps to use it:
1. Add annotations
The annotation API is based on Angular 2.0:
import { injectable, inject } from "inversify";
#injectable()
class Katana implements IKatana {
public hit() {
return "cut!";
}
}
#injectable()
class Shuriken implements IShuriken {
public throw() {
return "hit!";
}
}
#injectable()
class Ninja implements INinja {
private _katana: IKatana;
private _shuriken: IShuriken;
public constructor(
#inject("IKatana") katana: IKatana,
#inject("IShuriken") shuriken: IShuriken
) {
this._katana = katana;
this._shuriken = shuriken;
}
public fight() { return this._katana.hit(); };
public sneak() { return this._shuriken.throw(); };
}
2. Declare bindings
The binding API is based on Ninject:
import { Kernel } from "inversify";
import { Ninja } from "./entities/ninja";
import { Katana } from "./entities/katana";
import { Shuriken} from "./entities/shuriken";
var kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken);
export default kernel;
3. Resolve dependencies
The resolution API is based on Ninject:
import kernel = from "./inversify.config";
var ninja = kernel.get<INinja>("INinja");
expect(ninja.fight()).eql("cut!"); // true
expect(ninja.sneak()).eql("hit!"); // true
The latest release (2.0.0) supports many use cases:
Kernel modules
Kernel middleware
Use classes, string literals or Symbols as dependency identifiers
Injection of constant values
Injection of class constructors
Injection of factories
Auto factory
Injection of providers (async factory)
Activation handlers (used to inject proxies)
Multi injections
Tagged bindings
Custom tag decorators
Named bindings
Contextual bindings
Friendly exceptions (e.g. Circular dependencies)
You can learn more about it at https://github.com/inversify/InversifyJS
In the particular context of Node.js there is a hapi.js example that uses InversifyJS.

Resources