How to get i18n JSON file inside packages in monorepo structure?

262 views Asked by At

I am configuring a monorepo using the Yarn berry workspace (3.6x). The folder structure I'm organizing is as follows:

pakages
└── 
|  i18n
|   └── locales
|       ├── en
|       |   └── common.json
|       └── de
|           └── common.json
sevices
└── 
    └── next-js-project

I would like to put only the language pack (JSON File) in the i18n folder in consideration of scalability, and configure the other 18n config settings to be set inside each project.

However, I am not good at importing the json file.

Is there any way to do it?

// next-js-project/next-i18next.config.js
const path = require("path");
module.exports = {
  i18n: {
    locales: ["en", "ko"],
    defaultLocale: "en",
    localeDetection: false,
    defaultNS: "common",
    localePath: path.resolve("@mymonorepo/i18n/locales"),
    debug: true
  }
};
//index.tsx
export const getStaticProps = async ({ locale }) => {
  console.log("locale", locale);
  return {
    props: {
      ...(await serverSideTranslations(locale, ["common"], nextI18NextConfig))
    }
  };
};

...

Server Error Error: Default namespace not found at D:\User\My-monorepo\services\next-js-project@po\i18n\public\locales\en\common.json

In this way, the path is not caught as packages/i18n, and it is caught as the path of next-js-project inside my services.

How can I fix this problem?

1

There are 1 answers

0
Lucas Hendren On

So I think you will want to utilize the workspace feature in yarn.

Basically you need to declare your workspaces properly for your monorepo, I have an example config below for a package.json for your monorepo but there are potentially other ways to do it. This will setup your packages and services workspace

{
  "name": "my-monorepo",
  "private": true,
  "workspaces": ["packages/*", "services/*"]
}

Now update the path in next-i18next.config.js, you can use Yarn's Workspace feature to resolve the correct path to your language packs:

const path = require("path");
const { workspaces } = require("../../package.json"); // Adjust the path to your root package.json

module.exports = {
  i18n: {
    locales: ["en", "ko"],
    defaultLocale: "en",
    localeDetection: false,
    defaultNS: "common",
    localePath: path.resolve(
      __dirname, `../../${workspaces.packages}/i18n/locales` // Adjust the path based on your monorepo setup
    ),
    debug: true,
  },
};

From there it should hopefully resolve, you may need to fiddle with the individual paths a bit, the main part is ensuring workspaces.packages is correct. Ive included an additional monorepo beginner guide that will include more examples and help with this and an additional simple example.