尝试使用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';
发布于 2019-08-17 21:35:23
电子和ES模块
最新版本的Electron支持开箱即用的ES模块,因此我们本能地认为这是没有问题的:
<script type="module" src="my-element.js"></script>事情是这样的:如果你加载主文件from the local file system,所有其他的资源也是用file://协议请求的;然而,由于安全原因,HTML规范禁止用这样的协议加载ES模块(更多信息here)。
解决方案
为源文件提供服务
使用静态文件服务器,从http://localhost:<server_port>而不是文件系统加载index.html (即es-dev-server可以很好地与LitElement配合使用)。
使用模块捆绑器
比如Rollup或Webpack,所以你只需要像普通脚本一样加载捆绑包。通过这种方式,您可以利用树抖动来删除未使用的代码以及其他编译/捆绑的好处。
使用TypeScript/Babel
两者都可以将es模块语句转换为commonjs (require)。
使用commonjs的
电子的节点集成允许您require() CJS模块。
注册自定义协议
参见here。
关于捆绑包的说明
使用捆绑器可能看起来不方便,因为它将负载集中在单个js文件上;然而,在源文件几乎总是位于本地包中的Electron环境中-因此网络延迟不是问题-它甚至可能导致性能的提高。此外,Rollup和Webpack都支持代码拆分和动态导入,因此您仍然可以完美地遵循优化模式,如App Shell Model。
发布于 2021-10-16 20:34:47
你必须先导出你想导入的东西,然后你才能做一些事情。它在firefox上也应该工作得很好。
https://stackoverflow.com/questions/57416942
复制相似问题