javascript - 尝试导入项目时出现错误 "Strict MIME type checking is enforced for module scripts per HTML spec"

标签 javascript html electron mime-types lit-html

尝试使用 lit-html 为我们的 Electron 屏幕创建一些可重复使用的组件.当我尝试添加示例组件时,我遇到了错误。

使用 electron: ^5.0.6
尝试导入模块 my-element.js (大部分代码是示例代码,我只是想让它工作)

<head>
    <!-- Polyfills only needed for Firefox and Edge. -->
    <script src="https://unpkg.com/@webcomponents/webcomponentsjs@latest/webcomponents-loader.js"></script>
</head>
<body>
<!-- Works only on browsers that support Javascript modules like
     Chrome, Safari, Firefox 60, Edge 17 -->
<script type="module" src="my-element.js"></script>

模块my-element.js包含以下内容:
import {LitElement, html, css} from 'lit-html';

class MyElement extends LitElement {

  static get properties() {
    return {
      mood: {type: String}
    }
  }

  static get styles() {
    return css`.mood { color: green; }`;
  }

  render() {
    return html`Web Components are <span class="mood">${this.mood}</span>!`;
  }
}

customElements.define('my-element', MyElement);

页面加载时出现错误
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.

我尝试了不同的导入方式lit-html但没有解决这个错误。

前任。 import {LitElement, html, css} from '../../node_modules/lit-html/lit-html';
前任。 import {LitElement, html, css} from '../../node_modules/lit-html/lit-html.js';

最佳答案

Electron 和 ES 模块
最新版本的 Electron 支持开箱即用的 ES 模块,因此我们本能地认为这可以正常工作:

<script type="module" src="my-element.js"></script>
问题是:如果您加载主 HTML 文件 from the local file system ,所有其他资源也需要使用 file://协议(protocol);然而,出于安全原因,HTML 规范禁止使用此类协议(protocol)加载 ES 模块(更多信息 here)。
解决方案
提供源文件
使用静态文件服务器并加载 index.html来自 http://localhost:<server_port>而不是文件系统(即 es-dev-server 适用于 LitElement)。
使用模块捆绑器
例如 Rollup 或 Webpack,因此您只需将 bundle 加载为普通脚本即可。通过这种方式,您可以利用 tree shaking 来删除未使用的代码以及其他编译/捆绑优势。
使用 TypeScript/Babel
两者都可以将 es 模块语句转换为 commonjs ( require )。
使用commonjs
Electron 的节点集成允许您 require() CJS 模块。
注册自定义协议(protocol)
here .

关于打包机的说明
使用捆绑器可能看起来不方便,因为它将负载集中在单个 js 文件上;然而,在源文件几乎总是在本地包中的 Electron 环境中——因此网络延迟不是问题——它甚至可能导致性能提高。此外,Rollup 和 Webpack 都支持代码拆分和动态导入,因此您仍然可以完美地遵循优化模式,例如 App Shell Model .

关于javascript - 尝试导入项目时出现错误 "Strict MIME type checking is enforced for module scripts per HTML spec",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57416942/

相关文章:

javascript - 在 PHP 的 where 子句中使用 span 文本

node.js - 具有持久数据的NodeJS + RxDB + Electron

javascript - DOMParser parseFromString 仅在迭代结果主体 childNodes 时删除 Node

Electron - window.postMessage 在预加载和具有特定目标来源的渲染器之间进行对话

javascript - 将 Canvas 从一页复制到另一页而不超过最大字符限制

javascript - jquery 表折叠在 ie11.035 和 firefox 46.0.1 上不起作用

javascript - 使用 video.js 和 BigVideo 时无意中显示时间戳

javascript - Jquery FileReader 输入多个图像以缩略图显示

python - 如何通过添加<span>来修改Django的某部分内容,同时保持段落文本的原始格式?

javascript - HTML5 范围 - 不支持的伪 : range