tiny-invariant icon indicating copy to clipboard operation
tiny-invariant copied to clipboard

Exported as `.default` in CJS build

Open overlookmotel opened this issue 4 years ago • 4 comments

At present when requiring this library from CJS code (e.g. in Node), require('tiny-invariant') returns an object and you have to access the function from the .default property.

const invariant = require('tiny-invariant').default;

I know the purpose of this module is primarily for client-side code as then it can be effectively minimised in production builds. However, I like it so much, I now use it everywhere including pure Node.js code!

Would you consider reconfiguring the CJS builds so require('tiny-invariant') returns the actual invariant function?

To avoid breaking changes, it'd be possible to also export invariant as property .default of itself e.g.:

// Compiled CJS build
function invariant(condition, message) { /* ... */ }
invariant.default = invariant;
module.exports = invariant;

Or, to also issue a deprecation warning:

const warning = require('tiny-warning');
Object.defineProperty(invariant, 'default', {
  get() {
    warning(
      false,
      'Accessing `invariant` as `require('tiny-invariant').default` is deprecated.\n'
      + "Use `require('tiny-invariant')` (without `.default` instead)."
    );
    return invariant;
  }
});

How do you feel about this?

I'd be happy to submit a PR.

overlookmotel avatar Apr 07 '20 11:04 overlookmotel

hello? anyone home?

thanpolas avatar Jul 18 '21 16:07 thanpolas

@thanpolas I published an alternative simple-invariant designed for use in NodeJS from CommonJS (although importing from ESM works fine too).

overlookmotel avatar Jul 18 '21 16:07 overlookmotel

I cannot reproduce this issue, see https://stackblitz.com/edit/node-znq7it:

❯ npm run test
$ node ./lib/test.js
console.log after successful invariant usage!

Maybe some change since this issue was opened fixed the issue?

pkerschbaum avatar Sep 28 '22 20:09 pkerschbaum

Thanks for looking into this @pkerschbaum!

alexreardon avatar Sep 29 '22 05:09 alexreardon