1

Maybe I completely forgot how ES6 import/export works, but I want to be able to do something like this:

import { b } from 'folder';

and not load all of the other exported files from the folder index file.

This is what I currently have:

├── folder
│   ├── file1.js
│   ├── file2.js
│   ├── file3.js
│   └── index.js
├── test.js


//file1.js:
console.log("in file1");
export const a = 3 + 4;

//file2.js:
console.log("in file2");
export const b = 3 + 5;

//file3.js:
console.log("in file3");
export const c = 3 + 6;

//index.js:
export * from "./file1";
export * from "./file2";
export * from "./file3";

//test.js:
import { b } from "./folder";
console.log(`this is ${b}`);

The problem is that when doing this it loads the other two files (a and c) as well, shown by the output:

in file1
in file2
in file3
this is 8

How can I import various files from folder without having to use specific file import:

import { b } from "./folder/file2";

as I might have to import quite a lot of files from that folder, and I wish I could use import destructuring.

So instead of:

import { b } from "./folder/file2";
import { c } from "./folder/file3";

I want to be able to use:

import { b, c } from "./folder";

but without having to load the other files from the folder (a in this case).

Vlad
  • 997
  • 1
  • 5
  • 18
  • Similar question here(You can make use of some of the workarounds mentioned in this thread) : https://stackoverflow.com/questions/29722270/is-it-possible-to-import-modules-from-all-files-in-a-directory-using-a-wildcard – Bala Jun 26 '20 at 10:14

1 Answers1

0

How can I import various files from folder without having to use specific file import, you can't. Exports are determined during runtime, which means that the index.js file needs to be evaluated in order to determine what should be exported.

However you can design your files in such a way that evaluating them doesn't run any business code.

For example:

//file1.js:
export const Module1 = () => {
  console.log("in file1");
  return ({
    a: 3 + 4,
  });
}
//test.js
import { Module1 } from "./folder";
const { a } = Module1();
Olian04
  • 6,480
  • 2
  • 27
  • 54