Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/react-declarative/react-i18n-jsx-factory

The easiest way to setup i18n without changing any existing code. By using JSX runtime this tool will localize third party libraties too
https://github.com/react-declarative/react-i18n-jsx-factory

i18n internationalization jsx jsx-factory jsx-runtime jsx-syntax react react-i18n translation

Last synced: about 1 month ago
JSON representation

The easiest way to setup i18n without changing any existing code. By using JSX runtime this tool will localize third party libraties too

Awesome Lists containing this project

README

        

# react-i18n-jsx-factory

> The easiest way to setup i18n without changing any existing code. By using JSX runtime this tool will localize third party libraries too

![screenshot](./docs/screenshot.png)

## Contribute

> [!IMPORTANT]
> Made by using [react-declarative](https://github.com/react-declarative/react-declarative) to solve your problems. **⭐Star** and **💻Fork** It on github will be appreciated

## How is it works

Since 17 version React provides a new version of the JSX transform

```tsx
/* Before transpile */

function App() {
return

Hello World

;
}

/* After transpile */
import { jsx as _jsx } from 'react/jsx-runtime';

function App() {
return _jsx('h1', { children: 'Hello world' });
}

```

An idea is simple. Bundler replaces `react/jsx-runtime` and `react/jsx-dev-runtime` modules with interceptor

```js
const path = require(`path`);

module.exports = {
webpack: {
alias: {
'react/jsx-runtime': path.resolve(__dirname, './src/jsx-runtime'),
'react/jsx-dev-runtime': path.resolve(__dirname, './src/jsx-dev-runtime'),
}
},
};

```

The interceptor replaces `React.createElement` with `Translate.createElement` which provides localization

```js
const React = require('react');

const factory = (type, props) => {
if (window.Translate) {
const children = Array.isArray(props?.children) ? props?.children : [props?.children];
return window.Translate.createElement(type, props, ...children);
}
return React.createElement(type, props);
};

module.exports = {
Fragment: React.Fragment,
jsx: factory,
jsxs: factory,
};

```

So in a souce code we typing `lorem ipsum`

```tsx
import "./i18n";

import { createRoot } from "react-dom/client";

const wrappedApp = (

lorem ipsum

);

const container = document.getElementById("root")!;

const root = createRoot(container);

root.render(wrappedApp);

```

But `Translate.createElement` transforms it into `Hello world`

```ts
import React from 'react';

import { Translate } from 'react-declarative';

const locale = {
'lorem ipsum': 'Hello world!',
};

const translate = new Translate(locale);

window.Translate = translate;

Object.assign(React, {
createElement: translate.createElement,
});

```