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>
来源:oschina
链接:https://my.oschina.net/u/4307541/blog/3219174