johnnyshrewd
johnnyshrewd

Reputation: 1180

Export node.js class to be used with require()

I am exporting the following class:

export default class Tester {
}

The problem is that when I transpile this and import it with:

const Tester = require('./dist/Tester');

The problem is that to use the Tester class I need to use it like this:

const example = new Tester.Tester();

How can I export it so I do:

const example = new Tester();

Upvotes: 0

Views: 620

Answers (2)

Alan Darmasaputra
Alan Darmasaputra

Reputation: 468

The weird syntax is actually caused by you using 2 different import/export dialect, es6 and commonjs. Babel transpilation enables you to use both in the same system.

In es6

  • exports are written with export
  • imports are written with import

Example:

// -- es6

// tester.js

export default class Tester {}  // default export
export const SomeConsts = {}    // named export

// main.js

import Tester, { SomeConsts } from "./tester";

In nodejs implementation of commonjs

  • exports are written with module.exports
  • imports are written with require()

Example:

// -- commonjs

// tester.js

class Tester {}
const SomeConsts = {}

module.exports = { Tester, SomeConsts }  // arbitrary export

// main.js

const TesterModule = require("./tester.js");
const Tester = TesterModule.Tester;
const SomeConsts = TesterModule.SomeConsts;

// --or--

const { Tester, SomeConsts } = require("./tester.js");

Edit :

If you want Tester class to be the root of the export and still want to export SomeConsts, you'll have to make SomeConsts a part of Tester class.

// -- commonjs

// tester.js
class Tester {
  static SomeConsts = {}
}

module.exports = {}

// main.js

const Tester = require("./tester.js")
const TesterInstance = new Tester():

Upvotes: 2

Ben
Ben

Reputation: 3654

You could try amend the import block to use object destructuring:

const { Tester } = require('./dist/Tester');

Upvotes: 0

Related Questions