首页 > 解决方案 > Webpack 使用库的 ESM 部分,尽管它需要 CommonJS?

问题描述

我目前遇到一个奇怪的问题: Uncaught (in promise) ReferenceError: Cannot access 'Agile' before initialization,这可能是由于webpack试图将ESM我的库的一部分正确转换为CommonJs. 不幸的是,它做得不好,我最终遇到了上面提到的错误。

我的库同时支持:CommonJsESM. 所以我想知道为什么webpack使用该ESM部分并将其转换为CommonJs,而不是直接使用CommonJs我的库的部分?!

为什么我如此确定它与ESMtoCommonJs转换有关?

好吧,我曾经被迫通过删除支持webpack来使用CommonJs我的库的一部分。ESM通过这样做,我只是删除了库中ESM模块的路径package.json

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

在 unsupporting 之后ESM,webpack 被迫使用该CommonJs部分并且它按预期工作,因为 webpack 不再需要转换任何东西。(见图)

ESM转换为CommonJS[不工作] 在此处输入图像描述

未转化CommonJS[工作] 在此处输入图像描述

由于我的库应该同时支持 :ESMCommonJS,因此根本不支持ESM是没有解决方案的。

这是package.json我的图书馆:

{
  "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
}

也许我在package.json webpack中配置了一些错误的东西,ESM尽管它需要CommonJs

标签: javascriptreactjswebpackcommonjses6-modules

解决方案


好的,我通过解决所有问题解决了这个问题circular dependencies^^

参见:https ://github.com/agile-ts/agile/issues/193


推荐阅读