requirejs 使用

requirejs使用:
	
	**定义的模块要想其他文件能访问,需要最后添加return {键名:键值}的形式**
	**define()中的函数自动执行**
	
	1、定义模块(一个js文件一个模块):
		(1)函数式定义
			define(function(){...})
		(2)对象定义
			define({
				name:...,
				age:...
			})
		(3)存在依赖注入的函数式定义
			1、[]中的注入文件,如果是main.js设置的文件,直接写映射名,其他文件,
			要写基于main.js中baseUrl写的路径上添加具体路径和文件名

			2、define(['main.js中的映射文件名'],function(前面文件的形参){
				console.log($);//main.js文件中function对应的文件对象名
			})

代码示例:

main.js:

//配置文件
requirejs.config({
	//基础路径
	baseUrl:'js/', //表示js文件夹路径,也可以写具体路径
	//映射,.js省略,选择要加载的js文件
	paths:{
		'index':'apps/index',  //使用index就代表后面的文件
		'getname':'apps/getname',
		'jquery':'libs/jquery-3.4.1'
	}
})
//引入映射文件,function的形参是映射文件对象,对内部进行操作
requirejs(['index','getname','jquery'],function(index,getname,$){
//对指定文件中的函数进行调用,文件定义的模块必须有return才能被访问
	index.ori();
})

getname.js:

define(function(){
// 	var userInfo={
// 	 name:'jeff',
// 	 age:18
// 	}
// //使得外部能够访问
// 	return{
// 		userInfo:userInfo
// 	}

	function create()
	{
		return '文本'
	}

	return {
		create:create
	}
})

index.js:


define(['getname','jquery'],function(getname,$){
	//访问其他文件内容
	 console.log(getname.userInfo.name+getname.userInfo.age);

	// 用法一:当前文件调用其他文件function
	 $('#root').html(getname.create());
	
	//用法二,由main.js中的function调用
	function ori()
	{
		$('#root').html(getname.create());
	}

	return{
		ori:ori
	}
})

html文件:

<html>
<head>
	<meta charset="utf-8">
	<title ></title>

	<script data-main='js/main.js' src='js/libs/require.js'></script>	

	<style>

	</style>
</head>
<body >

//通过requirejs增加元素
<div id='root'></div>

<script>

</script>

</body>
</html>

发布了317 篇原创文章 · 获赞 3 · 访问量 7165

猜你喜欢

转载自blog.csdn.net/weixin_43294560/article/details/104063921