Karl Morrison February 2016

TypeError: Cannot set property of undefined in module.exports

'use strict';
module.exports = function () {
    this.myVar = 'example';
    console.log(this.myVar);
};

I get the error:

/home/karl/mymodule.js:3
    this.myVar = 'example';
               ^

TypeError: Cannot set property 'myVar' of undefined

Answers


Oxi February 2016

in strict mode, this is undefined.

but in non-strict mode this is nothing but pointing to GLOBAL.

so here, you are trying to set something on undefined, so the error

where exactly, were you intending to attach myVar ?

on your module ? or on GLOBAL ? if its on GLOBAL (which is actually a bad idea), use GLOBAL.myVar or global.myVar.

if its on your module you could do module.exports.myVar = 'example';

Post Status

Asked in February 2016
Viewed 2,657 times
Voted 13
Answered 1 times

Search




Leave an answer