Home > Enterprise >  Webpack uses ESM part of library although it requires CommonJS?
Webpack uses ESM part of library although it requires CommonJS?

Time:09-18

I'm currently having a weird issue: Uncaught (in promise) ReferenceError: Cannot access 'Agile' before initialization, which is probably caused by webpack trying to correctly transform the ESM part of my library into CommonJs. Unfortunately, it doesn't do a good job and I end up with the error mentioned above.

My library supports both: CommonJs and ESM. So I'm wondering why webpack uses the ESM part and transforms it into CommonJs, instead of directly using the CommonJs part of my library?!

Why am I so sure that it has something to do with the ESM to CommonJs transformation?

Well, I once forced webpack to use the CommonJs part of my library by removing the ESM support. By doing so, I simply deleted the path to the ESM module in the package.json of my library.

"module": "dist/esm/index.js"

After unsupporting ESM, webpack was forced to use the CommonJs part and it works as expected, since webpack doesn't have to transform anything anymore. (see image)

ESM transformed to CommonJS [not working] enter image description here

Untransformed CommonJS [working] enter image description here

Since my library should support both: ESM and CommonJS, simply unsupporting ESM is no solution.

Here is the package.json of my library:

{
  "name": "@agile-ts/core",
  "version": "0.2.0 17b078aa",
  "author": "BennoDev",
  "license": "MIT",
  "homepage": "https://agile-ts.org/",
  "description": "Spacy, Simple, Scalable State Management Framework",
  "keywords": [
    // ..
  ],
  "main": "dist/index.js",       // <!-- CommonJs
  "module": "dist/esm/index.js", // <!-- ESM
  "types": "dist/index.d.ts",
  "scripts": {
   // ..
  },
  "dependencies": {
    "@agile-ts/utils": "^0.0.8"
  },
  "peerDependencies": {
    "@agile-ts/logger": "^0.0.8"
  },
  "peerDependenciesMeta": {
    "@agile-ts/logger": {
      "optional": true
    }
  },
  "publishConfig": {
    "access": "public"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/agile-ts/agile.git"
  },
  "bugs": {
    "url": "https://github.com/agile-ts/agile/issues"
  },
  "files": [
    "dist",
    "LICENSE",
    "README.md",
    "CHANGELOG.md"
  ],
  "sideEffects": false
}

Maybe I've misconfigured something in the package.json and thus webpack uses ESM although it requires CommonJs?

CodePudding user response:

Ok, I fixed this issue by resolving all circular dependencies ^^

See: https://github.com/agile-ts/agile/issues/193

  • Related