【问题标题】:Getting error "Strict MIME type checking is enforced for module scripts per HTML spec" when trying to import project尝试导入项目时出现错误“对每个 HTML 规范的模块脚本强制执行严格的 MIME 类型检查”
【发布时间】:2019-12-16 10:06:52
【问题描述】:

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

使用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';

【问题讨论】:

    标签: javascript html electron mime-types lit-html


    【解决方案1】:

    电子和 ES 模块

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

    <script type="module" src="my-element.js"></script>
    

    问题是:如果你加载主 HTML 文件from the local file system,所有其他资源也使用file:// 协议请求;但是出于安全原因,HTML 规范禁止使用此类协议加载 ES 模块(更多信息here)。

    解决方案

    提供源文件

    使用静态文件服务器并从http://localhost:&lt;server_port&gt; 加载index.html 而不是文件系统(即es-dev-server 与LitElement 配合得很好)。

    使用模块捆绑器

    例如 Rollup 或 Webpack,因此您只需将 bundle 加载为普通脚本即可。通过这种方式,您可以利用 tree shaking 来删除未使用的代码以及其他编译/捆绑优势。

    使用 TypeScript/Babel

    两者都可以将 es 模块语句转换为 commonjs (require)。

    使用 commonjs

    Electron 的 Node 集成允许您require() CJS 模块。

    注册自定义协议

    here


    关于捆绑器的说明

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

    【讨论】:

    • 让我看看我是否理解正确,要使用 lit-html 或任何使用 ES6 模块的库,我们将不得不使用打包工具,例如 babel。
    • 在电子环境中,不幸的是,是的(不一定是捆绑器,上述解决方案中的其他解决方案可能会根据您的需要很好)。
    • 这是一个很好的解释!我发现的关于在浏览器中解决此问题的一个很好的补充:stackoverflow.com/questions/47403478/…
    【解决方案2】:

    你必须先导出你想导入的东西,然后你才能做事。它在 Firefox 上也应该可以正常工作。

    【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2022-08-14
    • 2021-08-02
    • 2017-03-27
    • 2021-03-07
    • 2021-05-30
    • 2021-06-05
    • 2017-10-02
    相关资源
    最近更新 更多