9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

requireJSでの依存関係の書き方

Last updated at Posted at 2012-12-20

やりたい事:ライブラリ「jquery」を読み込んだ後で「tmpl」を読み込む(依存関係)

リファクタ前

今までは、requireでネストしてた。
問題:依存が深くなるにつれて、名前で依存関係を解消したいと思ってくる。

require_before.js

require([
    "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"
],
function() {
    require([
        "http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"
        ,"../javascripts/libs/mylib.js"
    ],function(){
       //loaded();
    });
}
);

リファクタ後

requireJS pluginがそれに相当するらしい。

嬉しさ

  1. pathsで名前を付けられて、それで読み込み定義出来ること(define)
  2. shimによりその名前で依存関係を書ける事(shim)
  3. baseUrlを基底として、pathsのライブラリがロードされること。地味に便利
require_after.js

requirejs.config({
    shim: {
     'jquery.tmpl': ['jquery']
    },
    baseUrl : '../javascripts/libs',
    paths : {
        jquery : 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min'
        ,'jquery.tmpl' : 'http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js'
        mylibs : 'mylib'  // load "../javascripts/libs/mylib.js"
    }
});

define([ 'jquery','jquery.tmpl'], function() {
    alert($);
});

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?