我们正在制作一个 npm react 包(通过 tsdx 库),它是一个自定义钩子。安装此包的开发人员需要在根目录下创建一个config.json文件,并在其 Next.js 项目的公共文件夹中创建一个Languages.json文件。我们需要访问开发人员编写的这些文件中的信息。
打包文件:
LanguageProvider.tsx:存储当前语言环境状态的反应上下文。
UseTranslation.tsx:一个自定义钩子,它从上下文中获取语言环境并从 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;
}
包.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"
}
}
安装此包的 Next.js 项目:
公共/Languages.json
{
"en-us": {
"home": "Home",
"about": "About us"
},
"fa-ir": {
"home": "خانه",
"about": "درباره ما"
}
}
页面/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>
</>
);
}
当我运行该项目时,它会在浏览器控制台中显示此警告:
Warning: Did not expect server HTML to contain the text node "Home" in <div>.
at div
at Home
并且来自t函数的文本不会在页面上呈现。