简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM