NextJS: next-translate和yaml加载器

3

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

我自己尝试了一下,但没有成功:

// 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配置会引发以下错误:

Module parse failed: Unexpected token (1:8)
File was processed with these loaders:
 * ./node_modules/yaml-loader/index.js
You may need an additional loader to handle the result of these loaders.
2个回答

3

以下是使用YAML文件替代JSON文件的步骤,使用next-translate:

  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 格式。


1

就像 @Cequiel 描述的那样,解决方案是在 next.config.js 中使用 webpack 配置,但是我在使用 yaml-loader(0.6.0) 和 next.js (12.1.0 默认使用 webpack 5) 时存在兼容性问题,我尝试使用 js-yaml-loader(^1.2.2),效果很好。


你能否把你的回复作为评论发布在@cequiel下面,而不是作为答案呢? - Sasi V
1
当然可以,但是stackoverflow限制我在获得50个声望之前无法这样做... - Jack tse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接