
How to properly load YAML locale files in a Nuxt 3 application using nuxt-i18n.
Arthur Dufour
Have you ever tried loading YAML locale files inside your Nuxt 3 application using nuxt-i18n?
If you did, did you also come across the following error?
ERROR Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .yaml file format, or if it's an asset, add "**/*.yaml" to assetsInclude in your configuration.
This article shows you how to properly setup Nuxt so it knows how to handle YAML files.
The above error message states that Vite doesn't know how to handle YAML files by default; it requires a plugin for that.
@modyfi/vite-plugin-yamlSee the package on npmjs.com.
pnpm i -D @modyfi/vite-plugin-yaml
# or
# npm install -D @modyfi/vite-plugin-yaml
# or
# yarn add -D @modyfi/vite-plugin-yaml
Then register the Vite plugin inside your Nuxt config file.
// nuxt.config.ts
import ViteYaml from '@modyfi/vite-plugin-yaml'
export default defineNuxtConfig({
vite: {
plugins: [ViteYaml()],
},
})
Optionnaly, you can also add type definitions for .yaml or .yml modules.
// tsconfig.json
{
"extends": "./.nuxt/tsconfig.json",
"compilerOptions": {
"types": ["./types/index.d.ts", "@modyfi/vite-plugin-yaml/modules"]
}
}
Once Vite knows how to import yaml files, you can configure nuxt-i18n.
// i18n.config.ts
import en from './locales/en.yaml'
import fr from './locales/fr.yaml'
export default defineI18nConfig(() => ({
messages: {
en,
fr,
},
}))
And voilà 🎉 You should now be able to use translations from YAML files!
When I use YAML for my locale files, I like having my keys sorted alphabetically. For that, I'm using ESLint with yaml-eslint-parser.
I assume you already have setup ESLint in your project.
yaml-eslint-parserpnpm i -D yaml-eslint-parser
# or
# npm install -D yaml-eslint-parser
# or
# yarn add -D yaml-eslint-parser
Once the YAML parser module has been installed, you need to instruct ESLint to use it on .yaml and .yml files.
// .eslintrc.cjs
module.exports = {
overrides: [
{
files: ['*.yaml', '*.yml'],
parser: 'yaml-eslint-parser',
extends: ['plugin:yml/standard'],
rules: {
'yml/sort-keys': [
2,
'asc',
{
caseSensitive: true,
natural: true,
},
],
},
},
],
}