2

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);
Yerlan Yeszhanov
  • 2,149
  • 12
  • 37
  • 67
  • try this `export default function() {}` - documentation - https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export or this - https://stackoverflow.com/questions/37613507/export-a-function-with-node-js – martinho Aug 14 '18 at 11:10
  • Have you tried seperating the assigment to window from the export? `const addElement = ...; window.addElement = addElement; module.exports = addElement;` – Shilly Aug 14 '18 at 11:23
  • What is not working properly? Has node produced an `Error` we can look at? I feel like it _might_ be that `module.exports` by default wouldnt be an `Object`, you need to assign it an object or function or class or ... Anyhow, I feel like doing `module.exports.whatEverKey` should tell you that you cannot assign that key to a non-object, but I might be wrong. – somethinghere Aug 14 '18 at 11:24
  • There is no `window` object in *Node.js* modules – Bergi Aug 14 '18 at 12:27

1 Answers1

2

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
Willem van der Veen
  • 33,665
  • 16
  • 190
  • 155