RequireJS - jQuery 使用墊片配置



jQuery 使用墊片配置來定義 jQuery 外掛的依賴項,並透過宣告依賴項來設定模組值。

載入 jQuery

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

示例

以下示例使用 shim 配置來定義 jQuery 外掛的依賴項。建立一個名為 index.html 的 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 Tutorialspoint!!!</p>
   </body>
</html>

建立一個名為 app.jsjs 檔案,並在其中新增以下程式碼 −

//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();
   });
});

再建立一個名為 lib 的資料夾,以儲存 require.js 檔案和其他 js 檔案,如下所示 −

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
requirejs_jquery.htm
廣告