RequireJS教程:使用Shim Config的jQuery

jQuery使用填充程序配置来定义jQuery插件的依赖关系,并通过声明依赖关系来设置模块值。

加载jQuery

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

以下示例使用填充程序配置来定义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的jQuery

作者:terry,如若转载,请注明出处:https://www.web176.com/requirejs/1991.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2021年2月9日 下午5:17
下一篇 2021年2月9日 下午5:23

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注