NextJS: next-translate和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.

以下是使用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
}
})
  • 不要使用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格式。

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

    最新更新