我正在使用动态导入来创建项目中所有语言环境的块。块已创建,但客户端在运行时报告此错误:
Uncaught (in promise) ReferenceError: locale is not defined
at _callee$ (main.js?f161:72)
at tryCatch (runtime.js?98b8:62)
at Generator.invoke [as _invoke] (runtime.js?98b8:288)
at Generator.prototype.(:8082/d2/v2/search/anonymous function) [as next] (webpack-internal:///./node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:114:21)
at asyncGeneratorStep (asyncToGenerator.js?c973:3)
at _next (asyncToGenerator.js?c973:25)
有问题的代码:
// main.js
import { locale } from './config';
(async () => {
const formatter = new Formatter({ locale });
const i18n = new VueI18n({
locale,
formatter,
});
// Prints "en-GB", for example, so it's *not* undefined
console.log(locale);
const messages = await import(
/* webpackChunkName: "[request]" */
`./locales/${locale}/translations.js`, // <= Error
);
i18n.setLocaleMessage(locale, messages);
new Vue({
el: '#app',
router,
i18n,
render: h => h(App),
});
})();
巴贝尔配置:
"babel": {
"presets": [
"@babel/preset-env"
],
"plugins": [
[
"@babel/plugin-proposal-object-rest-spread",
{
"useBuiltIns": true
}
],
"@babel/plugin-transform-runtime",
"@babel/plugin-transform-async-to-generator",
"@babel/plugin-syntax-dynamic-import"
]
},
语言环境是这样导出的:
// config.js
export const locale = process.env.LOCALE; // e.g. "en-GB"
将导入路径更改为静态的东西,比如./locales/en-GB/translations.js
,有效。
编辑
locale
当我重新分配给中间变量时,这开始起作用,如下所示:
(async () => {
// ...
const tempLocale = locale;
// Passing `locale` here won't work, but `tempLocale` does...
const messages = await import(
/* webpackChunkName: "[request]" */
`./locales/${tempLocale}/translations.js`,
);
// `locale` is accepted just fine here, for some reason
i18n.setLocaleMessage(locale, messages);
// ...
})();
我还注意到,locale
在调试器中检查变量时,在 IIFE之外它解析为实际字符串(“en-GB”),但在它内部解析locale
为包含变量的模块。非常令人困惑,而且这个解决方案感觉太老套了,无法接受。