简体   繁体   中英

Import and export class problems

I wanted to write the class that will create a html node and everything works fine, but when i import it to file where i am creating object of this class and export this object to another js file, then it won't load (whole file where i imported this created object)

Class file

    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;
  }
}

Creating object

import Component from "../../js/core/component";

const docker = {
  article: new Component(
    "article",
    "article",
    '...'),
  ft: new Component("ft", "ft", `<li>Useful commands</li>`),
};

export { docker };

File that won't load

import { docker } from "../pages/docker/docker.js";
import Component from "./core/component.js";

document
  .querySelector(".inside")
  .insertBefore(docker.article.htmlComponent, document.querySelector(".ftWr"));

          ...
 

I think something is wrong with how you're using .insertBefore() , I changed the code to this and now it seams to work, for me at least...

document
  .querySelector(".ftWr").parentNode
  .insertBefore(docker.article.htmlComponent, document.querySelector(".ftWr"));

Edited: Nwm, I tried it out with liveServer instead of runing it through comandline and got an import error. For me it was solved by adding type="module" in the script tags, like this:

<script type="module" src="./index.mjs"></script>

Since the browser assumes common js imports if you don't tell it otherwise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM