konsumer / tplink-lightbulb

Control TP-Link smart lightbulbs from nodejs
MIT License
190 stars 32 forks source link

[ERR_REQUIRE_ESM] - when referencing the pkg as CommonJS #66

Closed PieterT2000 closed 2 years ago

PieterT2000 commented 2 years ago

When referencing your amazing package using,

const TPLSmartDevice = require('tplink-lightbulb')

I get this error image

I suspect the reason is that exports in package.json takes precedence over main according to the Node.js docs. I will shortly after create a pr with a workaround.

konsumer commented 2 years ago

I use microbundle to package for all, and that used to be the recommendation for setting it up, but they say, on their site, to do this now:

{
  "name": "foo",                      // your package name
  "type": "module",
  "source": "src/foo.js",             // your source code
  "exports": {
    "require": "./dist/foo.cjs",      // used for require() in Node 12+
    "default": "./dist/foo.modern.js" // where to generate the modern bundle (see below)
  },
  "main": "./dist/foo.cjs",           // where to generate the CommonJS bundle
  "module": "./dist/foo.module.js",   // where to generate the ESM bundle
  "unpkg": "./dist/foo.umd.js",       // where to generate the UMD bundle (also aliased as "umd:main")
  "scripts": {
    "build": "microbundle",           // compiles "source" to "main"/"module"/"unpkg"
    "dev": "microbundle watch"        // re-build when source files change
  }
}

So probly just need to make exports an object.

I can do a audit/update and add this change & publish.

konsumer commented 2 years ago

Sorry, didn't see the PR, but once CI is finished building my last commit, 1.7.10 should have it working. Please test and let me know if that resolve the issue.

PieterT2000 commented 2 years ago

A huge thank you David for responding so quickly! Keep up your great work!