docs: independent cache of menu data in different languages

This commit is contained in:
unix
2020-04-10 09:28:22 +08:00
parent 3bd35c0145
commit bad52262d9
3 changed files with 49 additions and 11 deletions

1
.gitignore vendored
View File

@@ -26,4 +26,3 @@ yarn-error.log*
.now
dist
/lib/data/

40
lib/use-locale.ts Normal file
View File

@@ -0,0 +1,40 @@
import { useRouter } from 'next/router'
import { useEffect } from 'react'
import useCurrentState from 'components/utils/use-current-state'
const DEFAULT_LOCALE = 'en-us'
const DEFAULT_TAB = 'guide'
export type LocaleTypes = {
locale: string
tabbar: string
}
const useLocale = (): LocaleTypes => {
const { pathname } = useRouter()
const [locale, setLocale, localeRef] = useCurrentState<string>(DEFAULT_LOCALE)
const [tabbar, setTab, tabRef] = useCurrentState<string>(DEFAULT_TAB)
useEffect(() => {
const names = pathname
.split('/')
.filter(r => !!r)
const currentLocale = names[0] || DEFAULT_LOCALE
const currentTabbar = names[1] || DEFAULT_TAB
if (currentLocale !== localeRef.current) {
setLocale(currentLocale)
}
if (currentTabbar !== tabRef.current) {
setTab(currentTabbar)
}
}, [pathname])
return {
locale,
tabbar,
}
}
export default useLocale

View File

@@ -3,7 +3,10 @@ const path = require('path')
const extractMetadata = require('extract-mdx-metadata')
const metaLocales = require('./locales')
const pagePrefix = path.join(__dirname, '../pages')
const targetPath = path.join(__dirname, '../lib/data/metadata.json')
const getTargetPath = locale => {
return path.join(__dirname, '../lib/data/', `metadata-${locale}.json`)
}
const weights = {
'guide': 1,
'docs': 2,
@@ -122,15 +125,11 @@ const deepTranslate = (metadata, locales) => {
}
}))
const jsonData = sortdMetaData.reduce((pre, current) => {
return {
...pre,
[current.name]: current.content,
}
}, [])
await fs.ensureFile(targetPath)
await fs.writeJson(targetPath, jsonData)
await Promise.all(sortdMetaData.map(async data => {
const targetPath = getTargetPath(data.name)
await fs.ensureFile(targetPath)
await fs.writeJson(targetPath, data.content)
}))
} catch (e) {
console.log(e)
process.exit(1)