Requirejs-jquery-shim-config

提供:Dev Guides
移動先:案内検索

RequireJS-Shim Configを使用したjQuery

jQueryはshim構成を使用してjQueryプラグインの依存関係を定義し、依存関係を宣言してモジュール値を設定します。

jQueryの読み込み

require(['jquery','jquery.myjsfile1','jquery.myjsfile2'], function($) {
   $(function() {
     //code here
   });
});

次の例では、 shim 構成を使用してjQueryプラグインの依存関係を定義します。 _indexl_という名前のhtmlファイルを作成し、それに次のコードを配置します-

<!DOCTYPE html>
<html>
   <head>
      <title>jQuery Shim Config</title>
      <script data-main = "app" src = "lib/require.js"></script>
   </head>

   <body>
      <h2>jQuery Shim Config</h2>
      <p>Welcome to finddevguides!!!</p>
   </body>
</html>

_app.js_という名前の js ファイルを作成し、その中に次のコードを追加します-

//You can configure loading modules from the lib directory
requirejs.config ({
   "baseUrl": "lib",

   "paths": {
      "app": "../app"
   },

   "shim": {
      "jquery.shim1": ["jquery"],
      "jquery.shim2": ["jquery"]
   }
});

//To start the application, load the main module from app folder
requirejs(["app/main"]);

_app_というフォルダを作成し、このフォルダから_main.js_モジュールをロードします-

define(["jquery", "jquery.shim1", "jquery.shim2"], function($) {
  //loading the jquery.shim1.js and jquery.shim2.js plugins
   $(function() {
      $('body').shim1().shim2();
   });
});

以下に示すように、require.jsファイルと他のjsファイルを保存する_lib_という名前のフォルダーをもう1つ作成します-

lib/jquery.shim1.js

$.fn.shim1 = function() {
   return this.append('<p>This is shim1 config...!</p>');
};

lib/jquery.shim2.js

$.fn.shim2 = function() {
   return this.append('<p>This is shim2 config...!</p>');
};

出力

ブラウザでHTMLファイルを開きます。次の出力が表示されます-

RequireJS Shim Config