Search code examples
javascriptecmascript-6babeljses6-module-loader

import from ES6 module to legacy js code


I use babel.js and have a new module foo in my code

foo.js:

export function foo(number) {
    return number + 42;
}

And bunch of big old files where everything is global. And I need to call a foo function from that legacy code.

bar.js:

 ...
 var result = foo(0); 
 ...

But I can't just import foo cause then my bar.js will be a module and unavailable from other old code. Is there a way to import module and retain my bar.js global?


Solution

  • I had a somewhat similar problem recently. I ended up polluting window object with everything I need in legacy code.

    I created separate register.js module for this purpose and included it to my webpack build:

    import ClassA from './ClassA'
    import ClassB from './ClassB'
    import * as utils from './utils'
    
    Object.assign(window, utils)
    Object.assign(window, {ClassA, ClassB})