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 :
- Named import:
import { export1, export2 } from "module-name";
- Default import:
import defaultExport from "module-name";
- Namespace import:
import * as name from "module-name";
- 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:
Named import
:
import {createNewElements} from "./CreateEle" // Your case
Default export
:
export default function createNewElements { //code here }
// In your imported module ex: index.js
import createNewElements from "./createEle"
This is quick-example :
create.js
:
export default function createNewElements() {
const allTask = [1, 2, 3];
return allTask;
}
index.js
import createNewElements from './create.js';
const taskArray = createNewElements()
function logTask() {
console.log(taskArray);
}
logTask();