如何导出功能?

时间:2018-08-14 11:09:18

标签: javascript node-modules

我正在尝试将此功能导出到另一个文件。但是它不能正常工作。只是想确保我做对了所有事情?

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

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

导出:

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

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

导入:

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

通话:

ColorAddElement.AddElement(addedElements);

1 个答案:

答案 0 :(得分:2)

假设您正在使用CommomJS模块系统,则应执行以下操作:

ColorAddElement(addedElements);

通过导出,您仅在以下代码部分中导出函数:

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

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

因此,require函数的变量中存储的值就是您导出的函数:

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