Yerlan Yeszhanov
Yerlan Yeszhanov

Reputation: 2439

How to export function?

I'm trying to export this function to another file. But It doesn't work properly. Just want to make sure am I doing everything right?

  window.colorAddElement = addedElements => {
    const addedElementsDOMNode = document.getElementById(
      `color-added-elements-"${num}"`,
    )

    if (colorAddNewClicked) {
      text = " "
      colorAddNewClicked = false
    }
    text += " " + addedElements
    addedElementsDOMNode.innerHTML = text
  }

exporting:

module.exports.AddElement =   window.colorAddElement = addedElements => {
    const addedElementsDOMNode = document.getElementById(
      `color-added-elements-"${num}"`,
    )

    if (colorAddNewClicked) {
      text = " "
      colorAddNewClicked = false
    }
    text += " " + addedElements
    addedElementsDOMNode.innerHTML = text
  }

Importing :

const ColorAddElement = require("./colorSet.js")

Calling :

ColorAddElement.AddElement(addedElements);

Upvotes: 2

Views: 427

Answers (1)

Willem van der Veen
Willem van der Veen

Reputation: 36620

Assuming you are using CommomJS module system you should do the following:

ColorAddElement(addedElements);

With the export you are only exporting a function in this code section:

module.exports.AddElement =   window.colorAddElement = addedElements => {
    const addedElementsDOMNode = document.getElementById(
      `color-added-elements-"${num}"`,
    )

    if (colorAddNewClicked) {
      text = " "
      colorAddNewClicked = false
    }
    text += " " + addedElements
    addedElementsDOMNode.innerHTML = text
  }

Therefore the value stored in the variable of the require function is the function which you exported:

const ColorAddElement = require("./colorSet.js"); // ColorAddElement is now your exported function

Upvotes: 2

Related Questions