'define' is not defined error on RequireJS & Webapp Yo generator

核能气质少年 提交于 2019-12-04 19:44:39

You load your scripts manually here and here, rendering the whole point of requireJS useless. You also load main first here config.js#L49.

Instead, you should only have this line in your index.html

<script data-main="scripts/config" src="scripts/vendor/requirejs/require.js"></script>

And load all your dependencies in that file (like you do with main) using define() and require(). As you have set exports, which sets the values as globals, the functions can be empty. Here's an sample:

define([
    "jquery",
    "underscore", 
    "backbone",
    "marionette",         
    "modernizr"
], function () {
        require([
        "backbone.babysitter", 
        "backbone.wreqr", 
        "text", 
        "semantic"
    ], function () {
        /* plugins ready */
    });

    define(["main"], function (App) {
           App.start();
    });
});

Also the baseUrl is the same as the directory as your data-main attributes folder (http://requirejs.org/docs/api.html#jsfiles):

RequireJS loads all code relative to a baseUrl. The baseUrl is normally set to the same directory as the script used in a data-main attribute for the top level script to load for a page. The data-main attribute is a special attribute that require.js will check to start script loading.

So I think your baseUrl in config.js points to scripts/scripts/-folder which doesn't exist. It could/should be vendor/ instead (and remove the vendor part from all of the declarations) or just left empty.

Instead of wiredep, you could try using https://github.com/yeoman/grunt-bower-requirejs which does similar things to wiredep but specially for bower/requirejs apps (see: https://github.com/stephenplusplus/grunt-wiredep/issues/7)

Your repo doens't include the dist-folder for jQuery, but otherwise here's a working sample of config.js: http://jsfiddle.net/petetnt/z6Levh6r/

As for the module-definition, it should be

require(["dependency1", "dependency2"])

and the module should return itself. Currently your main file sets itself as a dependency

require(["main", "backbone", "marionette"], function(App, Backbone, Marionette){

As you already set the backbone and marionette as globals with exports, you can again set the function attributes empty, so your main file should look like this:

require(["backbone", "marionette"], function(){
  "use strict";
  var App = new Backbone.Marionette.Application();

  App.addInitializer(function(){
    console.log("hello world!");
    Backbone.history.start();
  });

  return App;
});

And as you already use define to load main, don't require it again. Instead just call App.start() inside the define function.

https://jsfiddle.net/66brptd2/ (config.js)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!