1

I am creating a progressive web app using react and webpack. I have successfully configured everything and able to start the development. Now, i have many helper functions like :

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));
}

So, for this i have created another js file : helper.jsx. Now my helper.js contains the above function as it is. Now i want to use the above function in another react component.

I am doing a require in my component :

var helper = require("helper");

and trying to call the function using :

helper.getCookie('user');

Which is giving me helper.getCookie is not a defined. Please tell me how can i create a helper js and use the functions of helper js in my react components.

Uday Khatry
  • 449
  • 1
  • 8
  • 23
  • http://stackoverflow.com/questions/5311334/what-is-the-purpose-of-node-js-module-exports-and-how-do-you-use-it – chardy Jul 26 '16 at 17:12

1 Answers1

6

You need to export the function using 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
};
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thanx Ori, Just another question with a different context. I making some ajax calls in my project to a php file which is in my project's libraries folder. So how can i have my php files execute in webpack server? – Uday Khatry Jul 26 '16 at 17:12
  • is there any way i can execute the php files in webpack server? Or should i include the whole project in a different server which would be running in a different port? – Uday Khatry Jul 26 '16 at 17:16
  • As far as I know you can't execute php files in the webpack dev server, but I haven't touched PHP in eons. The 2nd solution should work, but you'll have to enable CORS on you PHP server, and I don't really know how to do that. – Ori Drori Jul 26 '16 at 17:20