Optimized CodeMirror with RequireJS AMD modules

CodeMirror is a great JavaScript library if you want to have a syntax-highlighted text area in a web page, but if you’re using AMD modules and want to use a compressed version, such as one from their minification helper on the CodeMirror site, you’re going to have a bad time. More specifically, you will get a mismatched anonymous define() modules error.

The first part of the solution is to build your own minified file using RequireJS’s optimizer, r.js. Download the files you want, making sure to keep the files in the proper folder structure (e.g. codemirror.js needs to be in its lib/ folder). Then us r.js with the modules you want to use. You don’t need to specify the core codemirror.js file to include, as r.js gathers dependencies automatically. For example:

 out: 'codemirror-html.js',
 include: ['mode/htmlmixed/htmlmixed']
//command line:
node path/to/r.js -o build.js
//folder structure where command is ran from:

Now, you will get a nice codemirror-html.js file that defines AMD modules nicely. To use the modules, you need to first require your new optimized file which will define the modules. Wrap the require of the modules to use in a require of the codemirror-html to ensure it is loaded first, so RequireJS doesn’t try to find the modules as path names:

require(['codemirror-html'], function() {
  require(['lib/codemirror', 'mode/htmlmixed/htmlmixed'], function(codeMirror) {
// your data-main file (optional - you could just write the full path in the outer require above)
 paths: {
 'codemirror-html': 'path/to/codemirror-html' // leave off the .js from the filename

And that should work! At least it does for me.

One thought on “Optimized CodeMirror with RequireJS AMD modules

Leave a Reply to Kanisha Milani Cancel reply

Your email address will not be published. Required fields are marked *