简体   繁体   中英

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();

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():

您可以尝试修改导入块以使用对象解构:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM