Cequiel
Cequiel

Reputation: 3777

NextJS: next-translate and yaml loader

Is it possible to use next-translate in combination with a YAML loader? For example, I'd like to use yaml-loader.

I tried it myself with no luck:

// 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
  }
})

the previous next.config.js configuration throws the following error:

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.

Upvotes: 3

Views: 4353

Answers (2)

Jack tse
Jack tse

Reputation: 61

just like what @Cequiel described, the solution is using webpack config in the next.config.js, but I have compatibility issues while using yaml-loader(0.6.0) together with next.js (12.1.0 which defaultly using webpack 5), I used js-yaml-loader (^1.2.2) works well.

Upvotes: 1

Cequiel
Cequiel

Reputation: 3777

These are the steps to use YAML files instead of JSON files with next-translate:

  1. Install yaml-loader:
yarn add yaml-loader --dev
  1. Configure webpack to use yaml-loader. This is my next.config.js file:
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. Do not use i18n.json. Instead use i18n.js. In my case I have two pages: home (/) and teachers:
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)
  }
}

And that's all! You can now use the human-friendly YAML format, instead of the machine-friendly JSON format.

Upvotes: 3

Related Questions