【问题标题】:Dynamic Import wrong path动态导入错误路径
【发布时间】:2021-11-10 13:13:54
【问题描述】:

我正在尝试根据 Next.js 提供的语言环境代码加载语言环境文件。但是每当我尝试进行动态导入时,就会发生错误并且导入路径错误:

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

要导入的代码:

    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 和 webpack 配置:

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

    return config
  }
}

编辑:

好的,我发现我的错误,文件被命名为index.de.json 而不是index.en.json。但我仍然想知道为什么错误消息显示了错误的路径。

【问题讨论】:

  • “文件名错误”和“路径错误”是一回事。

标签: javascript reactjs typescript next.js


【解决方案1】:

你可以试试这个方法。如果它不起作用,请检查@/locales/ 路径是否设置正确。

示例:

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

【讨论】:

    猜你喜欢
    • 2011-07-20
    • 1970-01-01
    • 2020-06-16
    • 2019-05-05
    • 2021-03-05
    • 2020-04-18
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多