首页 > 解决方案 > NextJS:下一个翻译和 yaml 加载器

问题描述

是否可以将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.

标签: internationalizationyamlnext.jsloader

解决方案


这些是使用 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 格式。


推荐阅读