Pos*_*stR 4 javascript import scope export class
大家好,我正在开发一个 Vanilla JS SPA 项目,我想实现 React 的一些原则,但只是用普通的 JavaScript。但是导入类有一个问题,我不确定发生了什么。我浏览了类似主题的一些答案,但到目前为止没有任何帮助。
于是就有了一个带有Class Tag的index.js文件。
import { banner } from './components/banner.js';
export class Tag {
constructor(parent, child, attribute, text) {
this.parent = parent;
this.child = child;
this.attribute = attribute;
this.text = text;
}
}
Tag.prototype.createTagElement = function() {
let parent = this.parent;
let child = this.child;
let attribute = this.attribute;
let text = this.text;
child = document.createElement(child);
parent.appendChild(child);
child.innerHTML = text;
for (let key in attribute) {
if (attribute.hasOwnProperty(key)) {
let value = attribute[key];
child.setAttribute(key, value);
}
}
return child;
}
Run Code Online (Sandbox Code Playgroud)
以及横幅组件 js 文件。
import { Tag } from '../index.js';
//Below from here there is only DOM structure writen in JavaScript;
// HTML DOM Site Structure based on my own custom Tag Class;
//Whole structure and code can be parted to independent components.
const body = document.querySelector("body");
const attribute = {"class": "test", "style": "background-color: red"};
//Site Banner
export const Banner = new Tag(
body,
"div",
{ "class": "banner" },
"Banner"
);
export const banner = Banner.createTagElement();
Run Code Online (Sandbox Code Playgroud)
我使用了几乎基本的 Webpack 配置,以及一些简单的插件和加载器。
如果我不将它们拆分为单独的文件,它会完美工作,但是当我尝试将其分开时,我有:
ReferenceError: can't access lexical declaration `Tag' before initialization main.4f842e.js line 469 > eval:2:95
<anonymous> webpack:///./src/index.js?:2
<anonymous> webpack:///./src/components/banner.js?:15
js http://localhost:8080/js/main.4f842e.js:457
__webpack_require__ http://localhost:8080/js/main.4f842e.js:20
<anonymous> webpack:///./src/index.js?:3
js http://localhost:8080/js/main.4f842e.js:469
__webpack_require__ http://localhost:8080/js/main.4f842e.js:20
<anonymous> webpack:///multi_(webpack)-dev-server/client?:2
0 http://localhost:8080/js/main.4f842e.js:480
__webpack_require__ http://localhost:8080/js/main.4f842e.js:20
<anonymous> http://localhost:8080/js/main.4f842e.js:84
<anonymous> http://localhost:8080/js/main.4f842e.js:87
Run Code Online (Sandbox Code Playgroud)
所以我请求帮助,为什么它不起作用?提前感谢您的帮助。
您必须消除循环(递归)引用,在循环引用中您可以在实例化对象之前使用该对象。换句话说,banner 应该包含一个 Tag 的实例(引用一个值),其类尚未定义(在初始化之前)。
您的index.js 导入banner
和banner.js 导入Tag
。因此,index.js 期望横幅包含Tag
已经Tag
定义的实例。banner.js正在尝试导入index.js,index.js正在尝试导入banner.js,它正在尝试导入index.js,等等。
从banner.js 中删除该import { Tag } from '../index.js'
语句并将Tag
定义从index.js 移至banner.js 应该可以解决该问题。