mwc.js 和 mwc.esm.js 有什么区别?

What is the difference between mwc.js and mwc.esm.js?

我创建了一个 StencilJS 项目,在我的 mwc 项目中捆绑了一堆 Web 组件。在 Stencil 中,我可以执行 npm run start 并看到我的组件按预期工作。

我创建了一个 Electron 项目,并在其中导入了 stencil mwc 包:

<script src="dist/mwc/mwc.js"></script>

当我这样做时,我注意到模板生成的代码无法 运行 遍历 MapSet 的任何 for 循环。基本上 for 循环退出并且从不迭代。

例如,在我的一个组件中,我有一个 class 以这种方式定义变量:

private _groupedItems : Map<string, Item[]> = new Map();

此变量被填充,当以下代码尝试 运行 时,它总是失败:

@Method()
async updateItemAsync( arg : { value : string, data : UpdateSelectItem } ) {
  //find where the item value is located
  let item : Item | undefined = undefined;
  for( const key of this._groupedItems.keys() ) {
    const groupedItems = this._groupedItems.get( key );
    if( groupedItems ) {
      item = groupedItems.find( item => item.value === arg.value );
      if( item ) {
        break;
      }
    }
  }
  if( item === undefined ) {
    console.error( 'Could not find item to update with value=', arg.value );
    return;
  }
  //NEVER GETS HERE!
  //more code below snipped out
}

在 Chrome devTools 中,我可以看到生成的 JavaScript 试图 运行 看起来像这样:

e.prototype.updateItemAsync = function(e) {
  return __awaiter(this, void 0, void 0, function() {
    var t, i, n, r, s;
    return __generator(this, function(a) {
      t = undefined;
      for (i = 0,
           n = this._groupedItems.keys(); i < n.length; i++) {
        r = n[i];
        s = this._groupedItems.get(r);
        if (s) {
          t = s.find(function(t) {
          return t.value === e.value
        });
        if (t) {
          break
        }
      }
    }
    if (t === undefined) {
      console.error("Could not find item to update with value=", e.value);
      return [2]
    }

我发现如果我不使用上述脚本,而是使用这个:

<script type="module" src="dist/mwc/mwc.esm.js"></script>

然后一切正常(有点)。基本上,当我使用 webpack 启动我的 Electron 包时,所有代码都按预期工作,我的 for 循环现在可以工作了。这个解决方案的问题是,当我使用 electron-webpack 打包我的 Electron 应用程序时,我无法 运行 生成独立的 EXE,因为我在应用程序启动时收到一条错误消息。 Chrome 在尝试加载 mwc.esm.js 文件时给我一个错误:

Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

mwc.js 和 mwc.esm.js 文件有什么区别?为什么 mwc.js 文件 运行 我的 for 循环不正确?

esm.js 文件是一个 Javascript Module 文件,将提供给支持它的浏览器。

当您使用包含 Stencil 组件 (/dist/mwc.js) 的旧方法时,您将收到有关如何正确包含它的控制台警告,版本 1 也记录了 in the breaking changes

[mwc] Deprecated script, please remove: <script src="/dist/mwc.js"></script>
To improve performance it is recommended to set the differential scripts in the head as follows:
<script type="module" src="/dist/mwc/mwc.esm.js"></script>
<script nomodule src="/dist/mwc/mwc.js"></script>

我不知道为什么 MapSet 循环不适用于非模块文件,但模块是 Chrome 中推荐的导入方式。

MIME 类型错误似乎是 a known issue in Electron,这似乎是因为 Electron 默认使用 file:// 协议,根据规范不允许包含模块。