I'm having a bit of a trouble understanding export/import mechanism when I have 3 files, each including the previous one.
Example:
//fileA.js:
export default MyClass {}
//fileB.js:
import MyClass from './fileA.js';
//fileC.js:
import './fileB.js';
My expectation is that MyClass
is then available in fileC, but it looks like it's just not the case. Can you advise?
I'm having a bit of a trouble understanding export/import mechanism when I have 3 files, each including the previous one.
Example:
//fileA.js:
export default MyClass {}
//fileB.js:
import MyClass from './fileA.js';
//fileC.js:
import './fileB.js';
My expectation is that MyClass
is then available in fileC, but it looks like it's just not the case. Can you advise?
- Possible duplicate of How to let parent module to import a child module of the child module in NodeJS – jmargolisvt Commented Aug 25, 2018 at 20:14
3 Answers
Reset to default 4Do like below:
//fileA.js:
export default MyClass {}
//fileB.js:
export { default as MyClass } from './fileA'
//fileC.js:
import { MyClass } from './fileB'
In your following code:
//fileA.js:
export default MyClass {}
//fileB.js:
import MyClass from './fileA.js';
//fileC.js:
import './fileB.js';
Myclass
is only going to be available in fileB because this is directly importing this. Your 3th line of code is not going to load in fileA. Just because FileA is loaded in FileB doesn't mean that the dependency gets transferred when we import B in FileC
To make it avialable, we have to import it again in file C like we did in file B:
import MyClass from './fileA.js';
Other import
export
syntax:
When one file exports multiple things (without the default in front) we can import it in the using named export for example:
export class1 {}
export class2 {}
We are exporting 2 classes, we could import them using the following syntax:
import {class1, class2} from './fileA.js';
Keep in mind that the names now have to match the names of the exports, class1
and class2
in this case.
We could also import all of the exports of a file in the following manner:
import * as classes from './fileA.js';
classes.class1 // the way to access class1
This syntax put all exports on an object of which we can determine the name (after the as
keyword). We then can access the exports like we normally access properties of an object.
When you import a module like this:
//fileC.js:
import './fileB.js';
it doesn't actually import any values. It will execute the global code in that module for side-effects, but does not import the values themselves. In order to do what you want to do, you will need to import module values in every file you want to use them.
See https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only