我希望制作一个在线的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"}
});
}
);
Require 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在我指定的路径中添加随机内容,那么它为什么这样做呢?我该如何使其正常工作?