简体   繁体   中英

ES6: Re-defining exported function

Given a 3rd party library that exports a function and uses this function in its internal logic - is there any way to re-define this function? For example:

third-party.js

export function a() {
 console.log('a');
}

export function b() {
 a();
}

my-module.js

import * as tp from 'third-party';

//Re-define, something like this
Object.defineProperty(tp, 'a', { writable: true, value: () => console.log('c')});

//Call b and get the re-define function called
tp.b(); //Expected output: 'c'

A few highlights:

  • I don't need it for testing, but for production (yes, I know it would be a dirty hack)
  • Yes, I'm aware of imports being live read-only views , I'm looking for a workaround to overcome this constraint
  • No, I can't change the code of the 3rd party library
  • I need my change to actually change the logic of the 3rd party. I'd like to call a function that calls a and not a itself.

Exported module is read-only. So, you can't do such.

delete tp.a;
tp.a = () => {
  console.log('c')
}
tp.a() // 'c'
tp.b() // You'll still get 'a'
// it's because, b is calling exported function a

If you wish tp.b() need the value overridden, then you don't export them but call in an instance. In your example code, just export a not b . But since, you're trying to override it from the third-party library. It's not possible to do so.

But if you insist using them, then you must override both functions.

const obj = {...tp}
obj.a = () => {
  console.log('c')
}

obj.b() // 'a'

obj.b = () => {
  obj.a()
}

obj.b() // 'c'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM