Search code examples
cdnsystemjscodemirror

With SystemJS, how do I map URLs between CDN libraries (CodeMirror)?


In my project, I want to use SystemJS to import a certain CodeMirror addon (xml-fold) from cdnjs.

However, that addon references main CodeMirror js through ../../lib/codemirror. This is resolved as https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/lib/codemirror, which is incorrect — should be https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/codemirror.js.

I tried to map wrong URL to the correct one, but it does not seem to be picked up — see below (error in browser console):

SystemJS.config({
    map: { 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/lib/codemirror': 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/codemirror.js' }
});

// in actual project I import it through a dependency, but the problem is the same
SystemJS.import('https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/addon/fold/xml-fold.js');
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.42/system.js"></script>

Error in console:

system.js:4 GET https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/lib/codemirror 403

What's the right way to map it?


Solution

  • It's possible to define a package for codemirror in SystemJS configuration and remap lib/codemirror to codemirror.js using package-local map setting:

    SystemJS.config({
        map: {
            'codemirror': 'https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0'
        },
        packages: {
            'codemirror': {
                map: {'./lib/codemirror':  './codemirror.js'}
            }
        }
    });
    

    This config should be enough to turn this import

    SystemJS.import('codemirror/addon/fold/xml-fold');
    

    into this url

    https://cdnjs.cloudflare.com/ajax/libs/codemirror/4.2.0/addon/fold/xml-fold.js'
    

    Then, relative path ../../lib/codemirror referenced from it will stay in the same package and will be remapped to ./codemirror.js. (I checked with current SystemJS version - 0.19.42)

    You might also want to add

        main: 'codemirror.js'
    

    to codemirror package config to be able to import codemirror itself as

     SystemJS.import('codemirror');
    

    if you need to do that.