0

I created a Things folder that has many Thing files and then create an index inside the Thing folder that acts as an "intermediate module".

Like this...

// things/thing1.js
console.log('thing1 loaded');

const thing1 = () => {
  console.log('Hi from thing1!');
};

export default thing1;
// things/thing2.js
console.log('thing2 loaded');

const thing2 = () => {
  console.log('Hi from thing2!');
};

export default thing2;

// things/index.js
export { default as thing1 } from './thing1';
export { default as thing2 } from './thing2';

When I import any of the files from the intermediate module...

// anotherFile.js
import { thing1 } from '../things';

thing1();

...all the files are loaded.

# console output
thing1 loaded
thing2 loaded # <-- don't want this to load.
Hi from thing1!

Other than...

import thing1 from './things/thing1';
import thing2 from './things/thing2';

...is it possible to structure the intermediate module or the import so only the file being imported is loaded?

2
  • 1
    Use tree shaking to remove unused exports, check out webpack Commented Aug 11, 2019 at 7:41
  • That wouldn't really make sense; your things/index.js has to load all of its modules in order to export them. The only way would probably be to use some bundler to minimize your JavaScript. Commented Aug 11, 2019 at 7:44

1 Answer 1

2

The general way your current code is set up, no, it's not possible. Whenever a module is imported, everything it imports will also be imported (and their top-level code will run).

One options is to change the thing1 and thing2 modules so that they export functions which, when run, load themselves - that way, their initialization can be run on demand, rather than whenever they're imported (side-effects that result from just importing often isn't a good idea anyway - better if the entry point alone can control when things start running):

// things/initThing1.js
export default () => {
  console.log('thing1 loaded');

  const thing1 = () => {
    console.log('Hi from thing1!');
  };

  return thing1;
};

and

// anotherFile.js
import { initThing1 } from '../things';

const thing1 = initThing1();
thing1();

(or you could initialize in the intermediate module, if other modules import from index.js)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.