我想制作一个在线javascript演示,我希望允许用户通过更改代码来改变演示行为。我的项目使用RequireJS取得了巨大的成功,所以我决定坚持下去。首先,我尝试通过绝对URL路径加载编辑器:
require(
[
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/codemirror.js",
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/mode/javascript/javascript.js",
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/addon/comment/continuecomment.js",
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/addon/edit/matchbrackets.js",
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/addon/comment/comment.js"
],
(CodeMirror)=>{
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
continueComments: "Enter",
extraKeys: {"Ctrl-Q": "toggleComment"}
});
}
);
要求JS尝试加载此路径:http://cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/lib/codemirror
这显然是错误的,因为
/lib/
放在我的路上,为什么会这样做?.js
缺失。在失败之后,我尝试配置requireJS并使用相对路径:
requirejs.config({
paths: {
codemirror: [
"//cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/"
]
},
waitSeconds: 20
});
require(
[
"codemirror/codemirror",
"codemirror/mode/javascript/javascript",
"codemirror/addon/comment/continuecomment",
"codemirror/addon/edit/matchbrackets",
"codemirror/addon/comment/comment"
],
(CodeMirror)=>{
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
continueComments: "Enter",
extraKeys: {"Ctrl-Q": "toggleComment"}
});
}
);
这一次,.js
存在,但路径仍然错误:http://cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4//lib/codemirror.js
注意双斜杠。
我没有要求RequireJS在我指定的路径中放置随机内容,为什么会这样做呢?我怎样才能做到这一点?
答案 0 :(得分:1)
问题在于,codemirror通常是打包的,codemirror.js
文件位于/lib
目录中,但是它在 cdnjs 上的托管方式是它在根目录。当您尝试加载一个加载项然后尝试加载../../lib/codemirror
时出现问题 - 由于上述托管差异而不存在该加载项。
我得到了类似的东西:
requirejs.config({paths:{
codemirror:'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.14.2',
'codemirror/lib':'https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.14.2'}
});
requirejs(["codemirror/lib/codemirror", "codemirror/addon/comment/continuecomment"],
function(CodeMirror) {
});