requireJs的用处和基本用法可参考https://www.runoob.com/w3cnote/requirejs-tutorial-1.html,简单来讲用处即是将一个较复杂功能的js文件拆分成多个功能较为简单易懂的js文件,而requireJs-text可将复杂html分块,我之前搭配使用了HandleBars即html模板使用,亲测对于一些需求动态生成Html实现较为简单,该文章只针对requireJs使用以及踩坑解决方法,如果只想查看text.js的跨域问题,从下半部分红色字体看起。
代码下载链接,涉及的工程目录如下:
node_modules中是一些需要的引入的js文件,index.html即最初界面,server.js是踩坑的解决方法,test.js测试require.js对js逻辑分块,test1.js测试requireJs-text对html逻辑分块,test1Tpl.html为待添加的html代码段。
基本用法可参考以上所给链接中教程1和教程2进行学习,亦可参考https://www.jianshu.com/p/c90fff39c225,注意的是在paths配置中js文件不要再带后缀.js,如下所示:
require.config({
paths : {
"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery",
"../node_modules/jquery/dist/jquery"],
"handlebars": "../node_modules/handlebars-v4.7.6",
"text": "../node_modules/requirejs-text/text",
"test": 'test',
"test1": "test1",
"tpl": "test1Tpl.html"
}
});
此处相当于定义了这些文件路径的缩写,可在其他模块中使用,代码中存在optimizeAllPluginResources: false,crossDomain: true这两项设置,可自行删除,当时解决跨域问题查资料说加设置,亲测加上此设置没用。
重点说下require-text的使用,在此工程中涉及的代码为test1.js和test1Tpl.html,如下:
define([
"jquery",
"handlebars",
"text!tpl"
], function($, handlebars, tpl){
function test() {
$('#testBody').closest('body').append(tpl);
alert('requireJs-text works~')
}
test();
});
<div>requirJs-text可html分块</div>
将此段html加载进主index.html主界面中展示,代码中因为是html文件,前端一定加上text!前缀,如果任性不加,默认他去取文件test1Tpl.html.js自动加后缀.js。
好啦,大坑来了,duang~duang~duang~,我是按照教程1教程2一步步,然后测试时直接将index.html扔进浏览器中直接展示,都是可以的,但是但是自己在此基础上学习html分块后,一加入text!tpl模板后报:
Access to XMLHttpRequest at 'file:///xxx/test-requireJs/testing/test1Tpl.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
此问题在ie浏览器中不存在,在google浏览器存在,翻阅各种资料后发现是---跨域问题---,如果想知道啥是跨域问题,参考http://blog.sina.com.cn/s/blog_816730ea0101ebe1.html,看了后也没怎么看懂,如有大牛能有更好的解释请留言,谢谢!但在此帖子中最后有个解决方法,即不可直接将html直接扔到浏览器中直接展示,要放在服务器后再通过http://localhost:8881/index.html展示。
使用node.js启动本地服务方法,可参考https://www.cnblogs.com/muou2125/p/10190118.html,我这里也简单描述下方法,很简单:
在文件夹下新建server.js文件,如下
var http=require('http'); //用来启服务
var fs=require('fs'); //用来读取文件
var root="需要修改为本地路径" //你本地放index.html页面的文件路径
//开启服务
var server=http.createServer(function(req,res){
var url=req.url;
var file = root+url;
fs.readFile(file,function(err,data){
if(err){
res.writeHeader(404,{
'content-type' : 'text/html;charset="utf-8"'
});
res.write('<h1>404错误</h1><p>你要找的页面不存在</p>');
res.end();
}else{
res.writeHeader(200,{
'content-type' : 'text/html;charset="utf-8"'
});
res.write(data);//将index.html显示在客户端
res.end();
}
})
}).listen(8881); //端口号
console.log('服务器开启成功');
注意:要修改root变量为本地的index.html路径,并在service.js所在目录下执行:node server.js,如图:
打开浏览器,输入:http://localhost:8881/index.html即可。
再次声明,文章仅是自行阶段性学习结果,存在局限性,如有不妥请留言指正,谢谢~
参考文献:
https://www.runoob.com/w3cnote/requirejs-tutorial-1.html
https://www.jianshu.com/p/c90fff39c225