Angular `build` 为使用 `webpack` 贴花的外部对象抛出错误

Angular `build` throw error for externals decaled with `webpack`

在我的 angular 中,我从外部加载 jquery 并且它有效。但是,在 build 之后,我得到一个错误 Uncaught ReferenceError: jQuery is not defined 。请注意,我的构建下载 jquery

问题:如何将 jquery 映射到我的构建?

index.html:

<script type="systemjs-importmap">
      {
        "imports": {
          "single-spa": "https://cdn.jsdelivr.net/npm/single-spa@5.8.2/lib/system/single-spa.min.js",
          "jquery": "https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"
        }
      }
    </script>

 <script>
      System.import("single-spa");
      System.import("jquery");
    </script>

webpack 配置(本地运行良好)

module.exports = {
  externals: {
    jquery: ["jQuery"],
  },
};

注意:构建后,如果我在服务器中运行它,我得到错误:

Uncaught ReferenceError: jQuery is not defined
    at Object.xeH2 (main-es2015.3ee70c890346f45d7daa.js:2)
    at l (runtime-es2015.cdfb0ddb511f65fdc0a0.js:1)
    at Module.zUnb (main-es2015.3ee70c890346f45d7daa.js:2)
    at l (runtime-es2015.cdfb0ddb511f65fdc0a0.js:1)
    at Object.0 (main-es2015.3ee70c890346f45d7daa.js:2)
    at l (runtime-es2015.cdfb0ddb511f65fdc0a0.js:1)
    at t (runtime-es2015.cdfb0ddb511f65fdc0a0.js:1)
    at Array.r [as push] (runtime-es2015.cdfb0ddb511f65fdc0a0.js:1)
    at main-es2015.3ee70c890346f45d7daa.js:2

我的服务器尝试从外部源下载 jquery

说明

当webpack externals是一个对象时,键是你在代码中导入的名称,值是运行时间环境中模块的名称。

webpack bundle 使用的“运行time environment”可以是全局变量或 SystemJS 模块注册表,具体取决于您的 webpack 配置对不同 libraryTargets 的 output.libraryTarget. The behavior of webpack externals 更改。

如果你的 libraryTarget 是 "system"(推荐用于 SystemJS 加载),"umd",或 "amd",那么这里的错误是 SystemJS 模块注册表中的模块名称是jquery,但您的 webpack 配置期望它是 jQuery。 SystemJS 模块名称区分大小写。

如果您的 libraryTarget 未指定或 var,则 webpack 将查找名为 jQuery 的全局变量。如果您正在使用额外的 systemjs amd.js,那么 jQuery 将不会被创建为全局变量。但是如果你没有使用amd.js,那么jQuery将被创建为一个全局变量。

可能的修复

  1. 更改您的 webpack 配置以期望 运行time 环境提供 jquery 而不是 jQuery。这仅在 webpack libraryTarget 为 systemumdamd 时有效(如上所述)。
// webpack.config.js
module.exports = {
    externals: {
        jquery: "jquery",
    },
};

该 webpack 配置相当于提供外部作为字符串数组:

// webpack.config.js
module.exports = {
    externals: ["jquery"]
};
  1. 从您的 index.html 文件中删除额外的 SystemJS amd.js。这将确保 jQuery 被创建为全局变量。然后确保 webpack 配置的 libraryTarget 未指定或 var.

进一步诊断

要诊断此处的问​​题,您可以 运行 在浏览器控制台中执行以下操作:

await System.import('jquery')

这将打印 jquery 模块是如何被 SystemJS 加载的。您应该单击记录的值以将其展开并查看键。您应该会看到您熟悉的 jquery 个函数。