在没有模块捆绑器的情况下导入 Web 组件

Importing web component without module bundler

我正在尝试按照 these 说明使用网络组件。我用 npm install --save @polymer/paper-button 安装了聚合物纸按钮,将下面的内容添加到我的 index.html 并用 vscode 的实时服务器打开它。但是我收到一个控制台错误:Uncaught TypeError: Failed to resolve module specifier "@polymer/iron-flex-layout/iron-flex-layout.js". Relative references must start with either "/", "./", or "../".。我想在不使用像 webpack 这样的模块打包器的情况下解决这个问题。

<script type="module" src="node_modules/@polymer/paper-button/paper-button.js"></script>
...
<paper-button raised class="indigo">raised</paper-button>

我发现的一个解决方法是改为使用 https://unpkg.com/,如下所示:

<script type="module" src="https://unpkg.com/@material/mwc-button@latest/mwc-button.js?module"></script>

注意:您需要将 ?module 参数添加到 URL 的末尾,以便 unpkg 修复所请求文件中的裸模块语法,否则它只是 returns带有裸模块导入的原始文件。

您遇到的错误是指浏览器(即使是支持 ES 模块的浏览器)无法解析裸模块导入 (import foo from 'bar';)。

是的,这里:

                           ↓
<script type="module" src="node_modules/@polymer/paper-button/paper-button.js"></script>

您正在通过相对路径导入,但 paper-button 又通过裸说明符导入其他模块:

paper-button.js:11:1
import '@polymer/iron-flex-layout/iron-flex-layout.js';

要了解有关浏览器中模块的更多信息以及缺乏对裸说明符支持的原因,我会推荐 this Damien Seguin 的文章。

您不一定需要模块捆绑器才能启动应用程序:polymer serve,Polymer 的开发服务器,自动解析模块说明符。此外,如果您不想手动配置构建系统,Polymer CLI 的 build 命令可能会有帮助,或者像 Babel 这样的工具可以帮助您 transform imports without bundling。