Webpack动态导入中的字符串文字

时间:2018-10-06 18:23:13

标签: webpack babeljs dynamic-import

我正在使用动态导入来创建项目中所有语言环境的块。创建了块,但是客户端在运行时报告此错误:

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

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

  // ...
})();

我还注意到,当在调试器中检查IIFE的 outside locale变量时,它解析为实际的字符串(“ en-GB”),但是为 inside 解析为包含locale变量的模块。非常令人困惑,并且此解决方案感觉太笨拙,无法接受。

0 个答案:

没有答案