我想写一个类,将创建一个html节点和一切工作正常,但当我导入它的文件,我正在创建这个类的对象和导出这个对象到另一个js文件,然后它不会加载(整个文件,我导入这个创建的对象)
类文件
export default class Component {
constructor(type, className, codeIn) {
this.codeIn = codeIn;
this.className = className;
this.type = type;
}
get htmlComponent() {
return this.codeConv();
}
codeConv() {
const temp = document.createElement(`${this.type}`);
temp.classList.add(`${this.className}`);
temp.innerHTML = `${this.codeIn}`;
return temp;
}
}
<<p>创建对象/strong>import Component from "../../js/core/component";
const docker = {
article: new Component(
"article",
"article",
'...'),
ft: new Component("ft", "ft", `<li>Useful commands</li>`),
};
export { docker };
无法加载的文件
import { docker } from "../pages/docker/docker.js";
import Component from "./core/component.js";
document
.querySelector(".inside")
.insertBefore(docker.article.htmlComponent, document.querySelector(".ftWr"));
...
我认为您使用.insertBefore()
的方式有问题,我将代码更改为此,现在它似乎可以工作,至少对我来说…
document
.querySelector(".ftWr").parentNode
.insertBefore(docker.article.htmlComponent, document.querySelector(".ftWr"));
编辑:我在liverver上尝试了一下,而不是通过命令行运行它,结果出现了一个导入错误。对我来说,它是通过在脚本标签中添加type="module"
来解决的,像这样:
<script type="module" src="./index.mjs"></script>
因为如果你不告诉它,浏览器会假设通用js导入