isl*_*obo 7 html javascript mime-types electron lit-html
尝试使用 为我们的 Electron 屏幕创建一些可重用的组件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>
Run Code Online (Sandbox Code Playgroud)
该模块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);
Run Code Online (Sandbox Code Playgroud)
当页面加载时我收到错误
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.
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的导入方式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 模块,因此我们本能地认为这可以正常工作:
<script type="module" src="my-element.js"></script>
Run Code Online (Sandbox Code Playgroud)
问题是:如果从本地文件系统加载主要 HTML 文件,所有其他资源也会通过该file://
协议请求;然而,出于安全原因,HTML 规范禁止使用此类协议加载 ES 模块(更多信息请参见此处)。
提供源文件
使用静态文件服务器并index.html
从http://localhost:<server_port>
文件系统加载(即es-dev-server
与 LitElement 配合良好)。
使用模块捆绑器
例如 Rollup 或 Webpack,因此您只需将包作为普通脚本加载即可。通过这种方式,您可以利用树摇动来删除未使用的代码以及其他编译/捆绑的好处。
使用 TypeScript/Babel
两者都可以将es模块语句转换为commonjs( require
)。
使用commonjs
Electron 的 Node 集成允许您使用require()
CJS 模块。
注册自定义协议
看这里。
关于捆绑器的注释
使用捆绑器可能看起来不方便,因为它将负载集中在单个 js 文件上;然而,在 Electron 环境中,源文件几乎总是位于本地包内 - 因此网络延迟不是问题 - 它甚至可能会提高性能。此外,Rollup 和 Webpack 都支持代码分割和动态导入,因此您仍然可以完美遵循App Shell Model等优化模式。