【问题标题】:Importing the same module twice throws ReferenceError两次导入相同的模块会引发 ReferenceError
【发布时间】:2021-08-27 13:30:47
【问题描述】:

我对 Javascript 还很陌生,必须维护这个不断增长的应用程序。我实现了一个新功能并成功地手动测试了它(应用程序在 dev 和 prod 模式下成功构建)。 但是当我使用vue-cli-service test:unit (mocha + chai) 运行测试时,会抛出运行时异常,说明:

Exception occurred while loading your tests`
ReferenceError: Cannot access 'serviceBase' before initialization

serviceBase.json:

import api from "./api";
import store from "./../store";
import i18n from "../../plugins/i18n";

export const serviceBase = {
  api: api,
  resource: "",
  preList: "me",
  preListOption: {
    getList: true
  },
{.....}

在多个地方使用,一个是documentImageService.js

import { createErrorMessage, serviceBase, clearance } from "../service";
import api from "../api";
import axios from "axios";

const DocumentImage = {
  ...serviceBase,
  clearance,
{.....}

现在,这个 const DocumentImage 用在两个地方。一个是renderer.js

import * as HB from "handlebars";
import { Helpers } from "@lextira/lexgate-document-renderer";
import DocumentImage from "@/store/utils/services/documentImageService.js";

export default class {
  /** @type {HB} */
  handlebars = undefined;
  /** @type {string} */
  clearanceToken = undefined;
{.....}

如果我在此处删除 DocumentImage 的导入,则测试运行不会出现进一步问题。 renderer.js 还没有测试,因为这是新实现的功能的一部分。 然而,正如介绍中已经说过的,当使用浏览器作为运行时,包括这个渲染器在内的一切都可以正常工作。但是这个import DocumentImage 似乎打破了“测试运行时”。

我猜这与 mocha 运行时的配置有关,但我无法从现有文档中找到问题所在。

【问题讨论】:

    标签: javascript vue.js testing mocha.js


    【解决方案1】:

    最终证明是循环依赖。即使我大部分时间都不相信它。

    DocumentImageStoreDocumentImageServiceServiceBaseNotificationStore

    由于 DocumentImageStoreNotificationStore 从同一个 vuex 存储解析,在某些情况下,依赖关系似乎没有得到解决,而在其他情况下它确实得到了解决(我猜这取决于首先要求哪个)。

    我通过在服务中为 NotificationStore 创建延迟导入来解决它:

    const getStore = () => import("./../store");
    
    export const createNotification = function(message) {
      getStore().then(store => {
        store.default.dispatch("notificationStore/createNotification", message)
      });
    }
    

    我想最好的办法是完全解决循环依赖,但目前我不知道如何按照现在的实现方式来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多