W
W
Worddoc2017-05-12 04:18:41
JavaScript
Worddoc, 2017-05-12 04:18:41

RequireJS. Why is the module undefined?

Hello.
Started learning Require js and got stuck right away.
Structure
folder
——main.js
——modules
————dom.js
————func.js

//main.js

requirejs.config({
  paths: {
    "func" : "modules/func",
    "dom": 'modules/dom'
  }
});

require(['func'],function(func){
  app.color();
});

//dom.js

var elem = document.querySelector('body');

//func.js

define(['dom'], function(dom) {
  var app = {
    color: function() {
      elem.style.background = 'red';
    }
  };

  return app;
});

Error: app is not defined.
Question: why is the module is undefined if I returned the module object through define? How to successfully load the func.js module with the dom.js dependency into the main.js config file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Kitmanov, 2017-05-12
@Worddoc

Important disclaimer: do not learn RequireJS, there are already native modules that will be available very soon directly in browsers and nodejs.
Read about scope in JS:
https://learn.javascript.ru/functions-closures
https://developer.mozilla.org/ru/docs/Web/JavaScri...
You can't just declare a variable in a module and expect that it will be available elsewhere. That's the point of modules. This module must be explicitly imported. In your case it will be something like this:

//main.js
requirejs.config({
    paths: {
        "app": "modules/app",
        "dom": 'modules/dom'
    }
});

require(['app'], function (app) {
    app.color();
});


//dom.js
define([], function() {
    return document.querySelector('body');
})


//app.js
define(['dom'], function (dom) {
    var app = {
        color: function () {
            dom.style.background = 'red';
        }
    };

    return app;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question