You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vanilla JS引入Clarity Core组件遇导入失败问题

解决Clarity Web组件在Vanilla JS项目中的导入错误

问题原因

浏览器原生ES模块不支持裸模块导入(即@cds/core/...这类包名形式的导入路径),它要求模块路径必须是相对路径(.//../)、绝对路径或完整CDN URL。Clarity官方文档的示例通常基于构建工具(如Webpack、Vite)编写,这类工具会自动解析裸模块,但纯HTML/Vanilla JS环境下需要手动调整导入路径。

解决方案

改用CDN的完整URL导入Clarity的Web组件模块,推荐使用unpkg或jsDelivr的ES模块分发版本。以下是针对你的项目的修改步骤:

  1. 替换所有@cds/开头的导入语句为对应CDN路径,以@cds/core v6版本为例:

    • 原导入:import '@cds/core/icon/register.js';
    • 修改为:import 'https://unpkg.com/@cds/core@6/icon/register.js';
    • 按钮组件的导入同理:import 'https://unpkg.com/@cds/core@6/button/register.js';
  2. 完整的修改后index.html代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Clarity Vanilla JS Button</title>
  <!-- 引入Clarity的全局样式 -->
  <link rel="stylesheet" href="https://unpkg.com/@cds/core@6/global.min.css">
</head>
<body>
  <cds-button status="primary">Hello Clarity</cds-button>

  <script type="module">
    // 注册图标组件
    import 'https://unpkg.com/@cds/core@6/icon/register.js';
    // 注册按钮组件
    import 'https://unpkg.com/@cds/core@6/button/register.js';
  </script>
</body>
</html>
  1. 验证效果:替换代码后,浏览器控制台的模块解析错误会消失,cds-button组件将正常渲染。

额外提示

  • 可以通过指定版本号(如@6)确保依赖版本稳定,避免自动升级带来的兼容性问题。
  • 如果需要使用更多Clarity组件,只需按照相同方式导入对应组件的register.js文件即可。

内容的提问来源于stack exchange,提问作者Rebolon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:28:14