我创建了一个 StencilJS 项目,其中在我的 mwc 项目中捆绑了一堆 Web 组件。在 Stencil 中,我可以执行 npm run start 并查看我的组件按预期工作。
我创建了一个 Electron 项目,并在其中使用以下命令导入 stencil mwc 包:
<script src="dist/mwc/mwc.js"></script>
当我这样做时,我注意到模板生成的代码无法运行任何迭代 Map 或 Set 的 for 循环。基本上 for 循环退出并且从不迭代。
例如,在我的一个组件中,我有一个类以这种方式定义变量:
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 循环现在正在工作。此解决方案的问题是,当我使用 electro-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
) 时,您将收到有关如何正确包含它的控制台警告,这也记录在 in the breaking changes 中。对于版本 1:
[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>
我不知道为什么 Map
和 Set
循环不适用于非模块文件,但模块是 Chrome 中推荐的导入方式。
MIME 类型错误似乎是 a known issue in Electron这似乎是因为 Electron 默认使用 file://
协议(protocol),根据规范不允许包含模块。
关于javascript - mwc.js 和 mwc.esm.js 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57575970/