npm包在webpack中的国际化支持如何实现?
{i18n.t('greeting', { name })}
;
}
```
5. 加载国际化资源
在Webpack启动时,加载国际化资源:
```javascript
i18n.init({
fallbackLng: 'en',
resources: {
en: {
translation: {
greeting: {
"Hello, {name}!",
},
},
},
zh: {
translation: {
greeting: {
"你好,{name}!",
},
},
},
},
});
```
案例分析
以下是一个简单的案例,展示如何在Webpack中实现npm包的国际化支持:
1. 项目结构
```
/src
├── components
│ └── Greeting.js
├── locales
│ ├── en.json
│ └── zh.json
├── index.js
└── webpack.config.js
```
2. webpack.config.js
```javascript
// ...其他配置
module: {
rules: [
{
test: /\.i18n\.js$/,
use: [
'babel-loader',
i18nextLoader({
loadPath: `${__dirname}/locales/[name]_[locale].json`,
}),
],
},
],
},
```
3. index.js
```javascript
import i18n from 'i18next';
import Greeting from './components/Greeting';
i18n.init({
fallbackLng: 'en',
resources: {
en: {
translation: {
greeting: {
"Hello, {name}!",
},
},
},
zh: {
translation: {
greeting: {
"你好,{name}!",
},
},
},
},
});
const root = document.getElementById('root');
root.appendChild({i18n.t('greeting', { name })}
;
}
export default Greeting;
```
通过以上步骤,我们可以在Webpack中实现npm包的国际化支持。在实际项目中,可以根据需要添加更多功能和插件,以满足不同场景下的国际化需求。
猜你喜欢:零侵扰可观测性