We are making an npm react package (by tsdx library) which is a custom hook. Developers who install this package need to make a config.json file at the root and a Languages.json file in the public folder of their Next.js project. We need to access the information in these files that the developer wrote.
Package files:
LanguageProvider.tsx: A react context that stores the current locale state.
UseTranslation.tsx: A custom hook that gets the locale from the context and finds the key from the current locale in Languages.json.
export function useTranslation() {
const { locale } = useContext(LanguageContext);
let LanguagesFile;
if (typeof window === 'undefined') {
const fs = require('fs');
LanguagesFile = fs.readFileSync("./public/Languages.json", 'utf8');
}
function t(key: string) {
if (typeof LanguagesFile !== 'undefined') {
const Languages = JSON.parse(LanguagesFile);
if (!Languages && !Languages[locale] && !Languages[locale][key]) {
console.warn(`No string '${key}' for locale '${locale}'`);
return false;
} else {
return Languages[locale][key].toString() || '';
}
}
}
return t;
}
package.json
{
"version": "0.1.0",
"license": "MIT",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"files": [
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"scripts": {
"start": "tsdx watch",
"build": "tsdx build",
"test": "tsdx test --passWithNoTests",
"lint": "tsdx lint",
"prepare": "tsdx build",
"size": "size-limit",
"analyze": "size-limit --why"
},
"browser": {
"fs": false,
"os": false,
"path": false
},
"peerDependencies": {
"react": ">=16"
},
"husky": {
"hooks": {
"pre-commit": "tsdx lint"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
},
"name": "react-intl",
"author": "Roya Shahroudi",
"module": "dist/react-intl.esm.js",
"size-limit": [
{
"path": "dist/react-intl.cjs.production.min.js",
"limit": "10 KB"
},
{
"path": "dist/react-intl.esm.js",
"limit": "10 KB"
}
],
"devDependencies": {
"@size-limit/preset-small-lib": "^5.0.4",
"@types/react": "^17.0.22",
"@types/react-dom": "^17.0.9",
"husky": "^7.0.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"size-limit": "^5.0.4",
"tsdx": "^0.14.1",
"tslib": "^2.3.1",
"typescript": "^4.4.3"
}
}
The Next.js project that installed this package:
public/Languages.json
{
"en-us": {
"home": "Home",
"about": "About us"
},
"fa-ir": {
"home": "خانه",
"about": "درباره ما"
}
}
pages/index.js
export default function Home({Languages}) {
const { locale, setLang } = useContext(LanguageContext);
const t = useTranslation();
return (
<>
<div>{t('home')}</div>
<button onClick={() => setLang('fa-ir')}>
Change Language To Persian
</button>
<button onClick={() => setLang('en-us')}>
Change Language To English
</button>
</>
);
}
When I run the project it shows this warning in the browser console:
Warning: Did not expect server HTML to contain the text node "Home" in <div>.
at div
at Home
and the text from t function doesn’t render on the page.