[英]Dynamic Import wrong path
I'm trying to load locale files based on the locale code given by Next.js.我正在尝试根据 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: tsconfig.json:
"baseUrl": ".",
"paths": {
"@/locales/*": ["locales/*"]
}
next.config.js with webpack config:带有 webpack 配置的 next.config.js:
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
.好的,我发现我的错误,文件被命名为index.de.json
而不是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.如果它不起作用,请检查@/locales/
路径是否正确设置。
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.