import from ES6 module to legacy js code
Asked Answered
T

1

2

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?

Trever answered 11/11, 2015 at 14:10 Comment(3)
"But I can't just import foo cause then my bar.js will be a module and unavailable from other old code" You have to import the module file / somehow if you want to use it. What's the context? How can bar.js be used "globally" in the first case.Cole
Which module loader are you using? Do you transpile to commonjs?Swat
I use webpack. In bar.js a lot of global variable and function that used in other part of application.Trever
P
4

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})
Pettigrew answered 12/11, 2015 at 11:5 Comment(1)
Great solution!Clothbound

© 2022 - 2024 — McMap. All rights reserved.