programing

RequireJS를 사용하여 백본 및 언더스코어 로드

lovejava 2023. 10. 6. 20:48

RequireJS를 사용하여 백본 및 언더스코어 로드

Require로 Backbone 및 Underscore(jQuery뿐만 아니라 백본 및 언더스코어)를 로드하려고 합니다.JS. Backbone과 Underscore의 최신 버전에서는 좀 까다로워 보입니다.하나는 언더스코어가 자동으로 모듈로 등록되지만 Backbone은 언더스코어를 전 세계적으로 사용할 수 있다고 가정합니다.백본이 모듈로 등록되지 않는 것 같아서 다른 립들과 다소 불일치하는 것 같습니다.이게 최고의 main.js 제가 생각해낼 수 있는 작품입니다.

require(
{
    paths: {
        'backbone': 'libs/backbone/backbone-require',
        'templates': '../templates'
    }
},
[
    // jQuery registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js',

    // Underscore registers itself as a module.
    'http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.2.1/underscore-min.js'
], function() {

    // These nested require() calls are just due to how Backbone is built.  Underscore basically says if require()
    // is available then it will automatically register an "underscore" module, but it won't register underscore
    // as a global "_".  However, Backbone expects Underscore to be a global variable.  To make this work, we require
    // the Underscore module after it's been defined from within Underscore and set it as a global variable for
    // Backbone's sake.  Hopefully Backbone will soon be able to use the Underscore module directly instead of
    // assuming it's global.
    require(['underscore'], function(_) {
        window._ = _;
    });

    require([
        'order!http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.5.3/backbone-min.js',
        'order!app'
    ], function(a, app) {
        app.initialize();
    })
});

저는 그것이 작동하는 동안, 옵티마이저가 그것을 억제한다는 것을 언급해야 합니다.저는 다음을 받습니다.

Tracing dependencies for: main
js: "/home/httpd/aahardy/requirejs/r.js", line 7619: exception from uncaught JavaScript throw: Error: Error: Error evaluating module "undefined" at location "/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js":
JavaException: java.io.FileNotFoundException: /home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js (No such file or directory)
fileName:/home/httpd/aahardy/phoenix/trunk/ui/js/../../ui-build/js/underscore.js
lineNumber: undefined
http://requirejs.org/docs/errors.html#defineerror
In module tree:
    main

이 문제를 더 잘 다룰 수 있는 방법이 있습니까?감사합니다!

RequireJS 2.X는 이제 새로운 구성을 사용하여 Backbone & Underscore와 같은 비AMD 모듈을 유기적으로 훨씬 더 잘 처리합니다.

shim (다를 들어, (1)합니다.deps), 만약 있다면, (이것은 다음의 것일 수 있습니다.paths구성, 또는 유효한 경로 자체일 수 있음) 에서 글로벌 되는 것이 사용하기만 (2) (선택 사항) 쉬밍할 파일에서 글로벌 변수 이름을 지정합니다. 이 이름을 필요로 하는 모듈 기능으로 내보내야 합니다. (내보내기를 지정하지 않으면 필요/정의 기능에 전달되는 것이 없으므로 글로벌을 사용하기만 하면 됩니다.)

은 입니다의 입니다.shim백본을 로드합니다.종속성이 없음에도 불구하고 언더스코어에 대한 내보내기도 추가됩니다.

require.config({
  shim: {
    underscore: {
      exports: '_'
    },
    backbone: {
      deps: ["underscore", "jquery"],
      exports: "Backbone"
    }
  }
});

//the "main" function to bootstrap your code
require(['jquery', 'underscore', 'backbone'], function ($, _, Backbone) {   // or, you could use these deps in a separate module using define

});

참고: 이 단순화된 코드는 jquery, backbone, 언더스코어가 이 "메인" 코드와 동일한 디렉터리에 있는 "jquery.js", "backbone.js", "undercore.js"라는 이름의 파일에 있다고 가정합니다.필수)의 URL입니다.그렇지 않은 경우 경로 구성을 사용해야 합니다.

는 개인적으로 된 로 합니다.shim기능성, 백본 & 언더스코어의 포크 버전을 사용하지 않는 것의 장점이 다른 인기 있는 답변에서 권장하는 AMD 포크를 사용하는 것의 장점보다 크지만, 어느 쪽이든 효과가 있습니다.

업데이트: 버전 1.3.0 기준 언더스코어에서 AMD 제거(필수)JS) 지원.

Amdjs/Backbone 0.9.1Amdjs/Underscore 1.3.1 포크는 James Burke(요구 관리자)의 AMD 지원을 받아 사용할 수 있습니다.JS).

언더스코어 백본에 대한 AMD 지원에 대한 자세한 정보.

// main.js using RequireJS 1.0.7
require.config({
    paths: {
        'jquery': 'libs/jquery/1.7.1/jquery',
        'underscore': 'libs/underscore/1.3.1-amdjs/underscore', // AMD support
        'backbone': 'libs/backbone/0.9.1-amdjs/backbone', // AMD support
        'templates': '../templates'
    }
});

require([
    'domReady', // optional, using RequireJS domReady plugin
    'app'
], function(domReady, app){
    domReady(function () {
        app.initialize();
    });
});

모듈이 올바르게 등록되어 있으며 주문 플러그인이 필요 없습니다.

// app.js
define([
    'jquery', 
    'underscore',
    'backbone'
], function($, _, Backbone){
    return {
        initialize: function(){
            // you can use $, _ or Backbone here
        }
    };
});

백본은 이제 의존성을 자체적으로 확보하기 때문에 언더스코어는 실제로 선택 사항입니다.

// app.js
define(['jquery', 'backbone'], function($, Backbone){
    return {
        initialize: function(){
            // you can use $ and Backbone here with
            // dependencies loaded i.e. Underscore
        }
    };
});

약간의 AMD 설탕을 사용하면 다음과 같이 쓸 수 있습니다.

define(function(require) {
    var Backbone = require('backbone'),
        $ = require('jquery');

    return {
        initialize: function(){
            // you can use $ and Backbone here with
            // dependencies loaded i.e. Underscore
        }
    };
});

Optimizer 오류와 관련하여: 빌드 구성을 다시 확인합니다.경로 구성이 꺼져 있는 것 같습니다.Require와 유사한 디렉토리 설정이 있는 경우사용할 수 있는 JS 문서:

// app.build.js
({
    appDir: "../",
    baseUrl: "js",
    dir: "../../ui-build",
    paths: {
        'jquery': 'libs/jquery/1.7.1/jquery',
        'underscore': 'libs/underscore/1.3.1-amdjs/underscore',
        'backbone': 'libs/backbone/0.9.1-amdjs/backbone',
        'templates': '../templates'
    }, 
    modules: [
        {
            name: "main"
        }
    ]
})

참고로 백본은 버전 1.1.1(~'13년 2월)부터 AMD 모듈로 등록하기도 합니다.shim config를 사용할 필요 없이 requirejs와 함께 작동합니다.(James Burke의 amdjs fork도 1.1.0 이후 업데이트되지 않았습니다.)

좋은 소식입니다. 언더스코어 1.6.0에서 requirejs define!!!

이 이하의 버전들은 심즈를 필요로 하거나 언더스코어를 필요로 합니다.js는 "_" 전역 변수가 박살나지 않기를 맹목적으로 바랍니다. (공정하게 말하면 공정한 내기입니다.)

간단히 싣습니다.

  requirejs.config({
    paths: {
        "underscore": "PATH/underscore-1.6.0.min",
    }
  });

제가 직접 적을 것이고, requirejs.org 에서 설명을 읽을 수 있으며, 일상적인 사용을 위해 아래 코드를 스니펫으로 사용할 수 있습니다. (p.s. 저는 여만을 사용합니다.) (많은 것이 업데이트되었기 때문에, 2014년 2월부로 이것을 게시합니다.)

인덱스 .html에 스크립트를 포함했는지 확인합니다.

<!-- build:js({app,.tmp}) scripts/main.js -->
<script data-main="scripts/main" src="bower_components/requirejs/require.js"></script>
<!-- endbuild -->

그러면 main.js.

require.config({
    shim: {
        'backbone': {
            deps: ['../bower_components/underscore/underscore.js', 'jquery'],
            exports: 'Backbone'
        }
    },

    paths: {
        jquery: '../bower_components/jquery/jquery',
        backbone: '../bower_components/backbone/backbone'
    }
});

require(['views/app'], function(AppView){
    new AppView();
});

app.js

/**
 * App View
 */
define(['backbone', 'router'], function(Backbone, MainRouter) {
    var AppView = Backbone.View.extend({
        el: 'body',

        initialize: function() {
            App.Router = new MainRouter();
            Backbone.history.start();
        }
    });

    return AppView;
});

내가 유용했길 바래요.

require.config({
  waitSeconds: 500,
  paths: {
    jquery: "libs/jquery/jquery",
    jqueryCookie: "libs/jquery/jquery.cookie",
    .....
  },

  shim: {
    jqxcore: {
      export: "$",
      deps: ["jquery"]
    },
    jqxbuttons: {
      export: "$",
      deps: ["jquery", "jqxcore"]
    }
    ............
  }
});

require([
 <i> // Load our app module and pass it to our definition function</i>
  "app"
], function(App) {
  // The "app" dependency is passed in as "App"
  // Again, the other dependencies passed in are not "AMD" therefore don't pass a parameter to this function
  App.initialize();
});

언급URL : https://stackoverflow.com/questions/8131265/loading-backbone-and-underscore-using-requirejs