We have answer of your question!

100% solved queries, no empty question

Question: Reacting to a module being imported or created in JavaScript ECMA2015


0

Suppose that we have a module declared like this.

import Stuff from "./stuff";
export default {
  things: { a: 1 },
  stuff: Stuff
}

Then we fetch it another module and use as shown below.

import Donkey from "./stuff-and-things"
console.log(Donkey.things.a);
console.log(Donkey.stuff.whatever-field);

I'd like to be able to react to the importing of the former into the latter, so that when Donkey will be created (added, incorporated, injected whatever it's called), a function will fire.

Something like this pseudo-code.

import Stuff from "./stuff";
export default {
  constructor: function(){ console.log("I'm alive!"); }
  things: { a: 1 },
  stuff: Stuff
}

Is it possible at all? I've been googlearching for a while now and I find nothing - no suggestions on how to nor denial of it. Possibly, I've been using wrong terms due to the ignorance of the subject.

Question author Konrad-viltersten | Source

Answer


1


There isn't a way to be notified when a module is imported. What you could do I guess is export a function instead. Then, in order to be do anything useful with that module, the function has to be called first.

For example:

// stuff-and-things
import Stuff from "./stuff";

const api = {
  things: { a: 1 },
  stuff: Stuff
};
export default function() {
  console.log("I'm alive!");
  return api;
};

// other
import stuffAndThings from "./stuff-and-things"
const Donkey = stuffAndThings();
console.log(Donkey.things.a);
console.log(Donkey.stuff.whateverField);
Answer author Felix-kling

Tickanswer.com is providing the only single recommended solution of the question Reacting to a module being imported or created in JavaScript ECMA2015 under the categories i.e javascript , constructor , module , ecmascript-6 , . Our team of experts filter the best solution for you.

Related Search Queries:


You may also add your answer

Thanks for contributing an answer to Tick Answer!