require.js使用
- 2020 年 4 月 3 日
- 筆記
require.js使用
1.require.js介紹:可以幫助我們去管理項目的依賴關係,解決頁面的變數衝突。
2.新建以下目錄
app目錄:放的是我們自定義的模組邏輯
lib目錄:放的是一些第三方的插件
main.js:是所有模組的主入口文件
index.html:模板文件
2.目錄內容
// main.js // requirejs.config:require.js的配置項 requirejs.config({ // 基礎路徑 baseUrl: "js/", 模組的路徑 paths: { config: "app/config", view: "app/view", http: "app/http", index: "app/index", jquery: "lib/jquery", vue: "lib/vue" }, // 配置那些沒有使用define規範的第三方插件 shim: { // 要配置的第三方插件的名字,當然vue是支援的,只是一個例子 "vue": { // 第三方插件的依賴項 deps: [], // 導處去使用 exports: "vue" } } }) // 導入模組使用 requirejs([ "config", "view", "http", "index", "jquery", "vue" ], function (config, view, http, index, $, vue) { // 主入口函數 }) // config.js // define:用來定義自定義的模組,遵循define規範,第一個參數是需要導出使用的依賴項,第二個參數是一個回調函數,在函數中寫邏輯 // 項目的公共配置 define(function () { return { // 將需要使用的部分導出去 publicUrl: 'http://www.wwtliu.com', path: "/sxtstu/music/baidu/list.php" } }) // http.js // 網路請求文件 define(["jquery"], function ($) { function getMusicData(url, type ,callback) { $.ajax({ url, type, success (data) { callback(data) } }) } return { getMusicData } }) // view.js // 項目的視圖文件。負責網頁的渲染 define(["jquery"], function ($) { // 拿到數據遍歷插入到html元素中 function renderView (data) { $(data).each((index, item) => { $('#app').append("<div>" + item + "</div>") }) } return { renderView } }) // index.js // 所有模組的調用者 define(["http", "view", "config"], function (http, view, config) { const path = config.publicUrl + config.path + "?type=1&count=5&offset=0" http.getMusicData(path, "get" , data => { console.log(data) }) view.renderView([12,34,56]) // require.toUrl():生成相對模組的url var cssUrl = require.toUrl("./style.css") console.log(cssUrl) })
index.html頁面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"></div> </body> <!-- data-main載入主入口文件 --> <script async data-main="js/main.js" src="js/lib/require.js"></script> </html>