{"id":15308035,"url":"https://github.com/wscats/requirejs-demo","last_synced_at":"2025-08-21T10:31:59.388Z","repository":{"id":72736135,"uuid":"64717750","full_name":"Wscats/requirejs-demo","owner":"Wscats","description":"《RequreJS学习笔记》","archived":false,"fork":false,"pushed_at":"2019-09-09T03:09:38.000Z","size":151,"stargazers_count":198,"open_issues_count":1,"forks_count":38,"subscribers_count":12,"default_branch":"master","last_synced_at":"2024-12-10T08:51:10.123Z","etag":null,"topics":["amd","commonjs","component","module","requirejs","shim"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Wscats.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2016-08-02T02:36:58.000Z","updated_at":"2023-11-28T15:20:44.000Z","dependencies_parsed_at":null,"dependency_job_id":"5a2724fd-a258-4377-991e-315a6aedd614","html_url":"https://github.com/Wscats/requirejs-demo","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Wscats%2Frequirejs-demo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Wscats%2Frequirejs-demo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Wscats%2Frequirejs-demo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Wscats%2Frequirejs-demo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Wscats","download_url":"https://codeload.github.com/Wscats/requirejs-demo/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230507051,"owners_count":18236944,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["amd","commonjs","component","module","requirejs","shim"],"created_at":"2024-10-01T08:13:40.021Z","updated_at":"2024-12-19T22:08:53.047Z","avatar_url":"https://github.com/Wscats.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"## RequireJS\n\n**require.js加载js文件的好处**\n\n 1. 可以防止JS加载时候阻塞页面渲染（JS运行时候DOM停止渲染的情况）\n 2. 使用require.js调用的方式加载JS，不用在像以前那样多个`\u003cscript\u003e`标签引入JS文件\n\n所有代码的目录结构如图\n\n![这里写图片描述](http://img.blog.csdn.net/20160802220949367)\n\n[代码存放的Github地址](https://github.com/Wscats/requirejs-demo)\n\n## 传统的引入\n**start.html**\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cscript type=\"text/javascript\" src=\"js/require.js\"\u003e\u003c/script\u003e\n    \u003cscript type=\"text/javascript\" src=\"js/a.js\"\u003e\u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cp\u003ewsscat\u003c/p\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n传统方法引入可以看到会先弹出alert，内容被阻塞没有渲染\n\n**a.js**\n\n```js\nfunction cat() {\n    alert(\"hello\");\n}\ncat();\n```\n\n## require.js的引入\n**start.html**\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml\u003e\n\u003chead\u003e\n    \u003cscript type=\"text/javascript\" src=\"js/require.js\"\u003e\u003c/script\u003e\n    \u003cscript\u003e\n        require([\"js/a\"]);\n    \u003c/script\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003cp\u003ewsscat\u003c/p\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n\n**a.js**\n\n```js\ndefine(function () {\n    function cat() {\n        alert(\"hello\");\n    }\n    cat();\n})\n```\n现在应require里面写可以避免以前的写法导致alert弹窗时候页面的`p`标签内容被阻塞无法渲染\n\n现在这种写法格式是用define定义一个模块，并在页面中调用require方法引入\n\n要注意的是，require接受的是一个数组，它注入的依赖是一个数组，哪怕数组只有一个依赖，而它第二个参数则可以传入一个回调函数，就是党数组中的依赖都加载完毕后，执行这个回调函数，比如我们可以加载jQuery的依赖，然后再回调函数中调用jQuery的库\n\n```js\nrequire([\"js/a\"]);\n```\n## config方法\n我们可以在上面代码上继续改进，可以用require.js的config方法，通过paths属性，就不用每次都写这么长的引入地址，有点像angular的服务注册，然后在控制器中注入相应的服务\n\n**base.js**\n\n```js\nrequire.config({\n    paths: {\n        \"jq\": [\"http://wsa.wsscat.com/jquery\", \"js/jquery\"],\n        \"a\": \"js/wsscat\"\n    }\n})\n```\n注意加载模块时不用写.js后缀，写了会报错\n我们可以把配置这样引入到主页里面\n\n```html\n\u003cscript type=\"text/javascript\" src=\"js/require.js\"\u003e\u003c/script\u003e\n\u003cscript type=\"text/javascript\" src=\"js/base.js\"\u003e\u003c/script\u003e\n```\n##path属性\n用paths还有一个好处就是让我们配置多个路径去加载js，当我们请求第一个路径不成功时候，可以继续往后面请求第二个js路径代替\n![这里写图片描述](http://img.blog.csdn.net/20160802130441636)\n\n##data-main\n我们还可以这样引入，在require引入的script标签中加入**data-main**属性，后面就不用在显式用`\u003cscript\u003e`标签引入其他脚本文件了\n```html\n\u003cscript type=\"text/javascript\" data-main=\"js/base\" src=\"js/require.js\"\u003e\u003c/script\u003e\n```\n\n**base.js**\n```js\nrequire.config({\n    baseUrl: 'js',\n    paths: {\n        jq: [\"http://wsa.wsscat.com/jquery\", \"jquery\"],\n        a: \"wsscat\"\n    }\n})\nrequire([\"jq\", \"a\"], function () {\n    $('span').css('color', '#673AB7');\n});\n```\n可以看到已经成功加载到我们所需要的依赖了\n![这里写图片描述](http://img.blog.csdn.net/20160802151550959)\n\nRequireJS的模块语法允许它尽快地加载多个模块，虽然加载的顺序不定，但依赖的顺序最终是正确的，就是说模块是异步不按顺序加载，但使用的时候只要依赖的顺序正确那就会按依赖摆放的顺序执行\n\n上面我们可以把之前的代码改进成这样，用define采用AMD规范，把方法写进模块里面，并以对象传递出来\n**wsscat.js**\n```js\ndefine(\n    function () {\n        function fun1() {\n            alert(\"wsscat\");\n        }\n\n        function fun2() {\n            alert(\"autumns\");\n        }\n        return {\n            f1: fun1,\n            f2: fun2\n        }\n    }\n)\n```\n**base.js**\n```js\nrequire.config({\n    baseUrl: 'js',\n    paths: {\n        jquery: [\"http://wsa.wsscat.com/jquery\", \"jquery\"],\n        a: \"wsscat\"\n    },\n})\nrequire([\"jquery\", \"a\"], function ($, a) {\n    console.log($('span'));\n    $('span').css('color', '#673AB7');\n    console.log(a);\n});\n```\n\n然后注入a的JS，并依赖此服务，是输出a，就能看到我们刚才模块给的对象里面的两个函数\n\n![这里写图片描述](http://img.blog.csdn.net/20160802181235976)\n\n## 模块依赖另一个模块\n\n如果我们在一个依赖中还要再去依赖另一个JS，理解来相当于angular在服务中还需要注入其他服务来扩展\n我们就可以继续这样改，在define中加入一个数组，让我们想把需要的依赖给填充进去，记得回调函数里面需要把这个依赖也加进去形参里面\n**wsscat.js**\n\n```js\ndefine(['wsscat2'],\n    function (wsscat2) {\n        function fun1() {\n            alert(\"wsscat\");\n        }\n\n        function fun2() {\n            alert(\"autumns\");\n        }\n\n        return {\n            f1: fun1,\n            f2: fun2,\n            f3: wsscat2.f1\n        }\n    }\n)\n```\n**wsscat2.js**\n```js\ndefine(\n    function () {\n        function fun1() {\n            return \"wsscat2.js's wsscat\";\n        }\n\n        function fun2() {\n            return \"wsscat2.js's autumns\";\n        }\n        return {\n            f1: fun1,\n            f2: fun2\n        }\n    }\n)\n```\n上面我们就完成了wsscat这个模块依赖了wsscat2模块，然后再次输出新的对象方法\n\n![这里写图片描述](http://img.blog.csdn.net/20160802194021644)\n\n## shim(非AMD写法的兼容)导入单个变量\n\n当我们遇到非AMD兼容写法的时候，我们要可以用exports方法，注意的是export方法只能输出一个方法或者对象\n**base.js**\n```js\nrequire.config({\n    //可以把下面共同指向js文件夹写在这个位置\n    baseUrl: 'js',\n    //path可以让我省略冗长的地址信息\n    paths: {\n        //可以配置多个路径，当js请求不成功，可以有备选路径\n        jquery: [\"http://wsa.wsscat.com/jquery\", \"jquery\"],\n        //define中再依赖其他模块\n        a: \"wsscat\",\n        //define遵从AMD的写法\n        b: \"wsscat2\",\n        //export一个对象\n        c: \"wsscat3\",\n        //export一个函数\n        d: \"wsscat4\"\n    },\n    //非AMD规范时候的兼容写法\n    //export暴露出对应的对象和方法\n    shim: {\n        c: {\n            //导出对象\n            exports: \"obj\",\n        },\n        d: {\n            //导出方法\n            exports: \"fun4\"\n        }\n    }\n})\n//注入对应依赖，当依赖都请求成功后执行对应的回调函数\nrequire([\"jquery\", \"a\", \"c\", \"d\"], function ($, a, c, d) {\n    console.log($('span'));\n    $('span').css('color', '#673AB7');\n    console.log(a.f3());\n    console.log(c);\n    console.log(d);\n});\n```\nwsscat3.js\n\n```js\nfunction fun1() {\n    return \"wsscat3.js's wsscat\";\n}\n\nfunction fun2() {\n    return \"wsscat3.js's autumns\";\n}\nvar obj = {\n    f1: fun1,\n    f2: fun2\n}\n```\nwsscat4\n\n```js\nfunction fun4() {\n    return \"wsscat4.js's wsscat\";\n}\n```\n上面我们就可以用exports方法分别把wsscats3和wsscat4里面的对象和方法暴露出来了\n\n## init(非AMD写法的兼容)导入多个变量\n\n```js\ne: {\n    init: function() {\n        return {\n            fun5: fun5,\n            fun6: fun6\n        }\n    }\n}\n```\n我们可以用init方法来导入多个变量，比shim属性导入单个零活，注意return里面的属性值是没有双引号的\n\n# require/text\n\n我们利用text插件为组件引入html和css\n\n使用npm下载`require/text`模块或者在github中下载[text.js](https://github.com/requirejs/text)文件\n\n```js\nnpm install requirejs/text\n```\n\n然后在配置文件\n\n```js\nrequire.config({\n    baseUrl: 'js',\n    paths: {\n        text: [\"text\"],//\u003c-添加这一个模块\n        jquery: [\"jquery\"],\n        bsheader: \"../extends/bsheader/bsheader\",\n        bsmain: \"../extends/bsmain/bsmain\",\n        bsfooter: \"../extends/bsfooter/bsfooter\",\n        bsmodal: \"../extends/bsmodal/bsmodal\"\n    }\n})\n\n//并注入对应依赖，当依赖都请求成功后执行对应的回调函数\nrequire([\"jquery\", \"text\", \"bsheader\", \"bsmain\", \"bsfooter\"], function ($, text, bsheader, bsmain, bsfooter) {\n    console.log(text);\n    $(\"bsheader\").bsheader();\n    $(\"bsmain\").bsmain();\n    $(\"bsfooter\").bsfooter();\n});\n```\n\n然后我们就可以在组件中这样引入css和html文件了，注意要先插入html到页面再绑定事件，不然事件会失效，并且引入html和css文件时候要记得这样引入`text!./bsfooter.html`text!加上文件路径的名字\n\n```js\ndefine([\"jquery\", \"text!./bsfooter.html\", \"text!./bsfooter.css\"],\n    function ($, html) {\n        var html = html;\n        return $.fn.extend({\n            bsfooter: function (option) {\n                return this.each(function () {\n                    $(this).html(html);\n                });\n            }\n        });\n    }\n)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwscats%2Frequirejs-demo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwscats%2Frequirejs-demo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwscats%2Frequirejs-demo/lists"}