2

Files look like this:

-test
--index.js
--test1.js
--test2.js

test1.js:

export const val1 = "TEST 1";
export const val2 = "TEST 2";
export const val3 = "TEST 3";
export const val4 = "TEST 4";

test2.js:

export const val5 = "TEST 5";
export const val6 = "TEST 6";
export const val7 = "TEST 7";
export const val8 = "TEST 8";

index.js:

import * as test1 from "./test1";
import * as test2 from "./test2";

export default { ...test1, ...test2 };

In another file:

import { val6 } from "./test";

The variable var6 is undefined.

However if I do this:

import test from "./test";
const { val6 } = test;

then var6 is defined and is equal to "TEST 6".

The test1 and test2 objects have the key __esModule: true.

I don't understand why this is the case. Why is var6 undefined in the first example?

markkazanski
  • 439
  • 7
  • 20
  • 3
    When you `export default { ... }`, the entire object literal is the default export, they are not named exports. `import { val6 }` uses the named export of `./test`, which doesn't exist, but `import test` and `const { val6 } = test` destructures the property `val6` from the default export of `./test` which is correct in this case. – Patrick Roberts Dec 12 '19 at 20:02
  • How do I combine exports from several files? – markkazanski Dec 12 '19 at 20:03
  • 3
    [Destructuring a default export object](https://stackoverflow.com/questions/43814830) – adiga Dec 12 '19 at 20:17

1 Answers1

4

As explained in the comments, you are creating a default-exported object literal, which is not the same as having named exports (it results in test referring to the combined object, but no other exports besides default). It seems what you are actually looking for is

// index.js:
export * from "./test1";
export * from "./test2";

With that, you can use

import { val6 } from "./test";
console.log(val6);
// or
import * as test from "./test";
console.log(test.val6);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375