Git Product home page Git Product logo

postor / next-i18n-helper Goto Github PK

View Code? Open in Web Editor NEW
8.0 3.0 1.0 1.07 MB

next 10 has i18n built in, so this project archived, for next 10 solution refer https://github.com/postor/next-i18n-loader. | next 10 已经支持多语言,所以这个项目存档,在 next 10 上的多语言方案可以参考 https://github.com/postor/next-i18n-loader

Home Page: https://www.youtube.com/watch?v=npC7orrLsvE&list=PLM1v95K5B1ntVsYvNJIxgRPppngrO_X4s

JavaScript 100.00%
nextjs i18next serverside-rendering

next-i18n-helper's Introduction

next-i18n-helper

next 10 has i18n built in, so this project archived, for next 10 solution refer https://github.com/postor/next-i18n-loader. | next 10 已经支持多语言,所以这个项目存档,在 next 10 上的多语言方案可以参考 https://github.com/postor/next-i18n-loader


i18n for next.js | 给 next.js 适配多国语言

quick glance: https://www.youtube.com/watch?v=npC7orrLsvE&list=PLM1v95K5B1ntVsYvNJIxgRPppngrO_X4s

usage | 使用

install | 安装

npm install next-i18n-helper --save

components/i18n.js -- config your i18n | 配置你的 i18n

import I18nHelper from 'next-i18n-helper'
import getWrapper from 'next-i18n-helper/dist/wrapper'

export const i18nHelper = new I18nHelper({
  defaultLang: 'en',  // 默认语言
  supportLangs: ['en','zh'] // 支持的语言列表
})

export const wrapper = getWrapper(i18nHelper)

server.js

...
const cookieParser = require('cookie-parser')
...

app.prepare()
  .then(() => {
    const server = express()
    server.use(cookieParser()) // next-i18n-helper use cookie to store user choose language | 使用 cookie 保存用户所选语言
    server.use('/static', express.static('public')) // publish your translation for xhr translate | 用于 xhr 翻译

    server.get('*', (req, res) => {
      return handle(req, res)
    })
    ...    
  })

basic

refer basic | 参考 basic

pages/index.js

...
import { wrapper } from '../components/i18n'

const translateNS = ['index']

const Index = ({ t }) => (<div>
  <Header />
  <h1>{t('My Blog')}</h1>
  ...
</div>)


const TIndex = translate(translateNS)(Index)
TIndex.translateNS = [...translateNS, ...Header.translateNS]

export default wrapper(TIndex)

with layout | 使用 _app.js

refer layout | 参考 layout

components/layout.js

import { wrapper } from './i18n'
import Header from './Header'
export default (Page) => {

  const Layout = () => (<div>
    <Header />
    <Page />
  </div>)

  return wrapper(Layout, [
    ...Header.translateNS,
    ...Page.translateNS
  ])
}

change language | 切换语言

components/Header.js

import { useState } from 'react'
import { i18nHelper } from '../components/i18n'

const translateNS = ['common']

const Header = () => {
  const [lang, setLang] = useState(i18nHelper.getCurrentLanguage())
  return (<p>
    ...
    <select value={lang} onChange={(e) => {
      i18nHelper.setCurrentLanguage(e.target.value)
      setLang(e.target.value)
    }}>
      <option value="en">English</option>
      <option value="zh">中文</option>
    </select>
    ...
  </p>)
}

## config | 配置

/**

  • I18nHelper */ export default class I18nHelper {

/**

  • Creates an instance of I18nHelper.
  • @param {Object} opt
  • @param {string} [opt.forceInitalLanguage = 'en'] force inital language(cookie=>forceInitalLanguage=>browser-setting=>default)
  • @param {string} [opt.defaultLang = 'en'] default language(cookie=>forceInitalLanguage=>browser-setting=>default)
  • @param {string[]} [opt.supportLangs = ['en']] support languages
  • @param {string} [opt.langCookieName = 'lang'] cookie to remember selected language
  • @param {number} [opt.langCookieExpire = 365] cookie expires in xxx days
  • @param {string} [opt.localesBaseUrl = '/static/locales'] locale file location
  • @param {Object} [opt.i18nOption] to extend i18next config
  • @param {module[]} [opt.plugins] i18next plugins, default cache and xhr for browser side
  • @memberof I18nHelper */ constructor(opt = {}) { ...
for more refer [src/index.js](./src/index.js)

next-i18n-helper's People

Contributors

dependabot[bot] avatar postor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

lambrojos

next-i18n-helper's Issues

Warning: Text content did not match. Server

I'm getting the following warning on your browser console when I select the Chinese language, It error on server-side rendering.

react-dom.development.js?61bb:88 Warning: Text content did not match. Server: "我的博客" Client: "My Blog" in h1 (created by Index) in div (created by Index) in Index (created by withI18nextTranslation(Index)) in withI18nextTranslation(Index) (created by Layout) in div (created by Layout) in Layout (created by Wrapper) in Wrapper (created by App) in App in ErrorBoundary (created by ReactDevOverlay) in ReactDevOverlay (created by Container) in Container (created by AppContainer) in AppContainer in Root

Default lanaguage is not working

I have changed the Chinese language as a default language, but it still using English as default.

export const i18nHelper = new I18nHelper({ defaultLang: 'zh', supportLangs: ['en', 'zh'] })

Example website is not working

I'm new about next.js, so I want to take a quick look at your example. but the URL is not working. Maybe you can fix it if it is convenient for you. Thanks a lot!

  • ERR_CONNECTION_REFUSED

Page props not updated on query paremeters change

Hi, first of all thanks for your work - this has taken me out of a really problematic situation :)
Anyway, I have observed that a wrapped page, if reached consecutive times with different parameters, won't update its initial props, for example:

Suppose we have a page accepting a query parameter, ( /video?id=123)
If inside the page there is a router link to another video (video?id=567), if I click it the page will render again, but the props wont update - the id in the address bar will be 567, but I will still be seeing the video with id 123.

I have tracked this down to here:
https://github.com/nextjs-boilerplate/next-i18n-helper/blob/master/src/wrapper.js#L44

If the same page gets rendered two times with different initial props, this.pageInitialProps the second time wont contain the updated properties.

I found out that update properties on subsequent loads end up in this.props.pageInitialProps, so modifying the Wrapper class render method in

render () {
    this.pageInitialProps = Object.assign(this.pageInitialProps, this.props.pageInitialProps)
    return <I18nextProvider i18n={this.i18n}>
      <Page {...this.pageInitialProps} />
    </I18nextProvider>
  }

actually solved my problem.

Is there a better way to do it? Or, If you are intereseted I can provide an example and/or a PR

thanks

請問可以在 nextjs6 中使用嗎?

請問可以在 nextjs6 中使用嗎?
目前在nextjs6 使用 i18next 有點問題,
不知道這個套件是否可以提供 nextjs6 的使用範例

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.