How to publish a library to npm that can be used both with import and require?

Viewed 217

tealium-tracker is written in es6 and transpiled using Babel before published to npm.

When consumers do:

import initTealiumTracker from "tealium-tracker";

everything works as expected.

However, some consumers want to use a require instead of an import, and have to append .default:

const initTealiumTracker = require("tealium-tracker).default;

How could I publish the library to avoid appending .default?

I want consumers to be able to do either:

import initTealiumTracker from "tealium-tracker";

or

const initTealiumTracker = require("tealium-tracker);

Source code

1 Answers

In your source code, If you are ok with using commonJS syntax for import and export...

One option would be to replace all import and export with require and module.exports. Looks like webpack doesn't allow mixing the syntaxes (ES6 and commonJS modules).

So your index.js file can require the functions from dependent module as

const { callUtag, flushUtagQueue } = require("./utagCaller");

and export the default function as

module.exports = initTealiumTracker;
module.exports.default = initTealiumTracker;

Likewise your dependent module can export the functions as

module.exports = { callUtag, flushUtagQueue };

This way, consumers should be able to use either

import initTealiumTracker2 from "tealium-tracker";

OR

const initTealiumTracker1 = require("tealium-tracker");
Related