userMod2
userMod2

Reputation: 8960

JS - Importing a single class using Import

I don't understand why I'm unable to import a specific class - I'm clearing misunderstanding something fundamental with module imports.

So say I have a index.js file called 'MyModule':

'use strict';

const One = require('./One.js');
const Two = require('./Two.js');
const Three = require('./Three.js');;

module.exports = {
  One,
  Two,
  Three
};

And say One.js looks roughly like:

'use strict';

class One {
   constructor(...) { ... }
   ...
}

module.exports = One;

When I go to use that module in my code, I'm currently doing:

const myMod = require('MyModule');

// Then I use it like so:

const something = new myMod.One(...)

This works fine, however why am I not allowed to do:

import { One } from require('MyModule')

In addition to why that doesn't work, is it beneficial to only import what I need to use?

Your explanations appreciated.

Thanks.

Upvotes: 0

Views: 158

Answers (1)

PotatoParser
PotatoParser

Reputation: 1058

There are two ways you can import by destructuring:

import { One } from 'MyModule' // This is only allowed within modules not on the main program

OR

const { One } = require('MyModule');

Upvotes: 1

Related Questions