NextJS:next-translate 和 yaml 加载器

问题描述

是否可以将 next-translate 与 YAML 加载器结合使用?例如,我想使用 yaml-loader

我自己尝试过,但没有运气:

Function GetNum(ByVal InString) As String
    Dim x As Integer
    Dim Ret As String
    
    For x = 1 To Len(InString)
        If Mid(InString,x,1) Like "[!0-9.() ]" Then Mid(InString,1) = Chr$(1)
    Next
    Ret = Trim(Replace(InString,Chr$(1),""))
    
    If Len(Trim(Ret)) = 0 Then GetNum = 0 Else GetNum = Ret
End Function

之前的 // file: next.config.js const nextTranslate = require('next-translate') module.exports = nextTranslate({ i18n: { locales: ['en','es','it'],defaultLocale: 'en' },loadLocaleFrom: (lang,ns) => require(`./locales/${lang}/${ns}`).then((m) => m.default),webpack: function (config) { config.module.rules.push({ test: /\.ya?ml$/,use: 'yaml-loader' }) return config } }) 配置抛出以下错误

next.config.js

解决方法

这些是在 next-translate 中使用 YAML 文件而不是 JSON 文件的步骤:

  1. 安装yaml-loader
yarn add yaml-loader --dev
  1. 配置 webpack 以使用 yaml-loader。这是我的 next.config.js 文件:
const nextTranslate = require('next-translate')

module.exports = nextTranslate({
  webpack: function (config) {
    config.module.rules.push({
      test: /\.ya?ml$/,type: 'json',use: 'yaml-loader'
    })
    return config
  }
})
  1. 不要使用 i18n.json。 而是使用 i18n.js。就我而言,我有两个页面:主页 (/) 和老师:
module.exports = {
  locales: ['en','es','it'],defaultLocale: 'en',pages: {
    '*': ['common'],'/': ['home'],'/teachers': ['teachers']
  },// Transform YAML files to JSON objects
  loadLocaleFrom: (lang,ns) => {
    return import(`./locales/${lang}/${ns}.yaml`).then((m) => m.default)
  }
}

仅此而已!您现在可以使用人类友好的 YAML 格式,而不是机器友好的 JSON 格式。