【发布时间】:2020-07-03 19:25:51
【问题描述】:
有一个函数我想导出到其他模块
index.js
export function addPageSwitchFunctionality() {
for (let i = 0; i < pages.length; i++)
pages[i].addEventListener("click", () => {
if (event.target.innerText === "Home")
document.location.href = "http://127.0.0.1:5500/public/";
else
document.location.href =
"http://127.0.0.1:5500/public/" +
event.target.innerText.toLowerCase();
});
}
addPageSwitchFunctionality();
somePage.js
import { addPageSwitchFunctionality } from "../index.js";
addPageSwitchFunctionality();
我的两个文件都有 html 类型的模块。当我运行 somePage.js 时,我收到一个错误,提示无法读取 null 的属性样式,这是 index.js 中的一行。这意味着我的整个文件被导入到 somePage.js 中。我怎样才能防止这种情况并只获得必要的东西?
更新:
错误:
Uncaught TypeError: Cannot read property 'style' of null
at index.js:165
第 165 行 index.js :
slideShow.style.backgroundImage = `url(${slideShowImages[slideIndex]})`;
【问题讨论】:
-
你能准确粘贴错误的内容吗?
-
好吧,我们假设 javascript 要知道哪些东西被导出并可供您导入,它必须编译整个源文件。
-
更大的问题是为什么一个正在导出方法的文件也执行该方法?
-
添加了错误和关键行。对于执行部分,它是一个导航栏,我想在页面之间共享一个功能。我知道它需要读取文件才能获得导出的功能。事情是出口在第27行,为什么找到它后没有停在那里?将功能原样复制到其他文件中是唯一的解决方案吗?
-
@Taplar,只有当我解决了这个问题时,我才明白你在说什么。所以我想做的是在主页中定义函数,从那里执行和导出它们,而不是在单独的文件中定义所有内容并将其导入主页和另一个页面,我很傻。
标签: javascript import module