Home > Mobile >  How to access Array of one child module from Parent module without using any library?
How to access Array of one child module from Parent module without using any library?

Time:01-01

I am using vanilla js to create task manager. I want to access returned array of imported module.

import * as createEle from './createEle.js';
const main = document.getElementById('main');
const add_task = document.getElementById('addTask');
const inProgress = [];

add_task.addEventListener('click', ()=>{
    addTask();
});

function addTask(){
     const taskArray=[inputTask, node, addButton]=createEle.createNewElements();
     console.log(taskArray);
}
This is exported module--

export function createNewElements(){
    const allTask = [];
    const inputTask = document.createElement("form");
    const node = document.createElement("input");
    const addButton = document.createElement("button");
    let key = Date.now();
    main.appendChild(inputTask);
    inputTask.appendChild(node);
    inputTask.appendChild(addButton);
    addButton.innerText = "Add Your Task";
    inputTask.setAttribute("class", "inputArea");
    node.setAttribute("key", key);
    node.setAttribute("placeholder", "Put Your Task Here");
    allTask.push(inputTask,node, addButton);

    return allTask;
}

I want to access the returned array allTask. But I'm getting error.

CodePudding user response:

Try import {createNewElements} as allTasks from './createEle.js';

CodePudding user response:

You Should know that there are :

  1. Named import:
import { export1, export2 } from "module-name";
  1. Default import:
import defaultExport from "module-name";
  1. Namespace import:
 import * as name from "module-name";
  1. Side effect import:
 import "module-name";

You used the default import:

import myDefault, * as myModule from "/modules/my-module.js";

While your export is a Named export

export function createELement(){...}

There 's a contreversation here!

To solve your issue you have two solutions:

  1. Named import :
import {createNewElements} from "./CreateEle" // Your case
  1. Default export :
export default function createNewElements { //code here }

// In your imported module ex: index.js

import createNewElements from "./createEle"

This is quick-example :

  1. create.js:
export default function createNewElements() {
  const allTask = [1, 2, 3];
  return allTask;
}

  1. index.js
import createNewElements from './create.js';
const taskArray = createNewElements()
function logTask() {
  console.log(taskArray);
}
logTask();

  • Related