I want to make an online javascript demo and I want to allow users to alter demo behavior through changing the code. My project uses RequireJS with big success so I decided to stick with it. First I tried to load editor through absolute URL paths:
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 tries to load this path then: http://cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4/lib/codemirror That's obviously wrong because
/lib/ in front of my path, so why did it do so?.js is missing.After that failure, I tried to configure requireJS and use relative paths:
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"}
});
}
);
This time, .js is there but the path is still wrong: http://cdnjs.cloudflare.com/ajax/libs/codemirror/5.13.4//lib/codemirror.js Notice the double slash.
I didn't ask RequireJS to put random stuff in the path I specified, so why does it do so? How can I make this work?
The problem is that codemirror is normally packaged such that the codemirror.js file is in the /lib directory, however the way it is hosted on cdnjs is that it's in the root directory. Your problem then arises when you try to load an add-on which then tries to load ../../lib/codemirror - which does not exist because of the aforementioned hosting difference.
I got it to work with something like this:
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) {
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With