Nightloewe
Nightloewe

Reputation: 1098

Dynamic Import wrong path

I'm trying to load locale files based on the locale code given by Next.js. But whenever I'm trying to do a dynamic import, an error happens and the import path is wrong:

Unable to load translation file "index": Error: Cannot find module './index.en.json'

Code to import:

    try {
        Object.assign(messages, await import(`@/locales/${name}.${locale}.json`))
    } catch(err) {
        console.log(`Unable to load translation file "${name}": ${err}`)
        error = err
    }

tsconfig.json:

    "baseUrl": ".",
    "paths": {
      "@/locales/*": ["locales/*"]
    }

next.config.js with webpack config:

module.exports = {
  reactStrictMode: true,
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
  webpack: (config) => {
    config.resolve.alias[`@/locales`] = path.resolve(__dirname, "locales")

    return config
  }
}

EDIT:

Okay, I found my mistake, the file was named index.de.json instead of index.en.json. But still I want to know why the error message shows a wrong path.

Upvotes: 0

Views: 677

Answers (1)

Asif vora
Asif vora

Reputation: 3347

You can try with this way. If it does not work please check @/locales/ path was correctly set.

Example:

  import(`@/locales/${name}.${locale}.json`).then((json) => {
    console.log(json)
    Object.assign(messages, json)
  }).catch((err) => {
    console.log(`Unable to load translation file "${name}": ${err}`)
    error = err
  });

Upvotes: 1

Related Questions