npmes6-modulesnpm-package

Convert "browser" fields in package.json to esm "exports"


I have a package that uses fields like this to hide the inclusion of node.js fs fields from the browser

{
  "name": "mypackage",
  "version": "1.0.0",
  "type": "module",
  "main": "dist/localFile.js",
  "module": "esm/localFile.js",
  "browser": {
    "./dist/localFile.js": false,
    "./esm/localFile.js": false
  }
}

How can I convert this same expression to the package.json "exports" field? Afaict the browser fields is ignored after exports are used. Everything that I have tried hasn't worked so far, I can elaborate if interested but it's probably cause more confusion to list attenpts, and if I can't get it working I have to be stuck with my package being cjs

Thanks!


Solution

  • I used this technique to solve this situation

    {
      "name": "mypackage",
      "version": "1.0.0",
      "type": "module",
      "exports": {
        ".": {
          "browser": {
            "import": "./esm/browser.js",
            "require": "./dist/browser.js"
          },
          "import": "./esm/index.js",
          "require": "./dist/index.js"
        }
      },
    

    and then i made a separate browser.js bundle that is a copy of index.js, but includes does not export the localFile class (or more precisely, actually exports a class that throws with a message "unimplemented" when you try to use it)