javascript - 两次导入同一个模块会引发 ReferenceError
问题描述
我对 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 运行时的配置有关,但我无法从现有文档中找到该问题所在。
解决方案
最终证明是循环依赖。即使我大部分时间都不相信它。
DocumentImageStore
→ DocumentImageService
→ ServiceBase
→ NotificationStore
。
从DocumentImageStore
同NotificationStore
一个 vuex-store 解析,在某些情况下,依赖项似乎没有得到解决,而在其他情况下它确实得到了解决(我猜这取决于首先要求哪个)。
我通过在服务中创建延迟导入来解决它NotificationStore
:
const getStore = () => import("./../store");
export const createNotification = function(message) {
getStore().then(store => {
store.default.dispatch("notificationStore/createNotification", message)
});
}
我想最好的办法是完全解决循环依赖,但目前我不知道如何按照它现在的实现方式来做到这一点。