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:
a
and not a
itself.Exports without a default tag are Named exports. Exports with the default tag are Default exports. Using one over the other can have effects on your code readability, file structure, and component organization. Named and Default exports are not React-centric ideas.
To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.
Use named exports to export a function in JavaScript, e.g. export function sum() {} . The exported function can be imported by using a named import as import {sum} from './another-file. js' . You can use as many named exports as necessary in a file.
Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With