dman dman - 6 months ago 50
Javascript Question

Browserify "module is not defined"

I am new to browserify. I tried the code below and got

Uncaught ReferenceError: module is not defined
when loading my web page. Everything is pretty plain and simple so not sure what I am doing wrong:

chronoOpenList.js:

module.exports = function getChronoOpenList() {
var xml = new XMLHttpRequest();
xml.open("GET", "api/nextrequestdue/", true);
xml.onreadystatechange = function () {
if (xml.readyState === 4 && xml.status === 200) {
var jsonText = xml.responseText;
parseChronoAndBuildElements(jsonText);
}
}
xml.send(null);
}


main.js:

var getChronoOpenList = require('./chronoOpenList');
getChronoOpenList();


html:

<script style="text/javascript" src="{% static 'js/bundle.js' %}"></script>


The command to browserify:

one@chat-dash /home/git/recognizer/recognizer_project/static/js $ /usr/local/lib/node_modules/browserify/bin/cmd.js main.js -o bundle.js


The bundle.js:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = function getChronoOpenList() {
var xml = new XMLHttpRequest();
xml.open("GET", "api/nextrequestdue/", true);
xml.onreadystatechange = function () {
if (xml.readyState === 4 && xml.status === 200) {
var jsonText = xml.responseText;
parseChronoAndBuildElements(jsonText);
}
}
xml.send(null);
}

....
},{"./chronoOpenList":1}]},{},[2])

Answer Source

The function parseChronoAndBuildElements is not defined in the scope of your getChronoOpenList function.

You need to define parseChronoAndBuildElements in that scope, like this:

chronoOpenList.js:

var parseChronoAndBuildElements = require('./parseChronoAndBuildElements.js');

module.exports = function getChronoOpenList() {
    var xml = new XMLHttpRequest();
    xml.open("GET", "api/nextrequestdue/", true);
    xml.onreadystatechange = function () {
        if (xml.readyState === 4 && xml.status === 200) {
            var jsonText =  xml.responseText;
            parseChronoAndBuildElements(jsonText);
        }
    }
    xml.send(null);
}