无法在带有require的webpack中使用自定义函数

Uda*_*try 1 require reactjs webpack

我正在使用react和webpack创建一个渐进的Web应用程序.我已成功配置所有内容并能够开始开发.现在,我有许多辅助函数,如:

function getCookie(name) {
      var start = document.cookie.indexOf(name + "=");
      var len = start + name.length + 1;
      if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
      }
      if (start == -1) return null;
      var end = document.cookie.indexOf(';', len);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(len, end));
}
Run Code Online (Sandbox Code Playgroud)

所以,为此我创建了另一个js文件:helper.jsx.现在我的helper.js包含上面的函数.现在我想在另一个反应组件中使用上述函数.

我在我的组件中做了一个要求:

var helper = require("helper");
Run Code Online (Sandbox Code Playgroud)

并尝试使用以下方法调用该函数:

helper.getCookie('user');
Run Code Online (Sandbox Code Playgroud)

哪个给了我helper.getCookie不是一个定义的.请告诉我如何创建一个帮助器js并在我的react组件中使用helper js的功能.

Ori*_*ori 5

您需要使用module.exports导出该函数:

function getCookie(name) {
      var start = document.cookie.indexOf(name + "=");
      var len = start + name.length + 1;
      if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
      }
      if (start == -1) return null;
      var end = document.cookie.indexOf(';', len);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(len, end));
}

module.exports = {
    getCookie: getCookie
};
Run Code Online (Sandbox Code Playgroud)