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

Vite Vue项目导入Stencil组件库时触发ERR_ABORTED 504错误

Vite Vue项目引入Stencil Web组件库的动态导入错误解决方法

问题背景

在Vite 4.0.4创建的Vue应用中,引入自行开发的StencilJS组件库@arnab7/cheesejs后,使用<checker-board>组件触发以下错误:

GET http://localhost:5174/node_modules/.vite/deps/checker-board.entry.js?import net::ERR_ABORTED 504 (Gateway Timeout)
TypeError: Failed to fetch dynamically imported module: http://localhost:5174/node_modules/.vite/deps/checker-board.entry.js?import undefined
index-e0c21bd2.js:917 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'isProxied') at initializeComponent (index-e0c21bd2.js:917:23)

组件库在Create React App中可正常运行,推测是Stencil的懒加载机制与Vite模块解析逻辑冲突,已尝试重启服务、重装依赖、清理缓存等方法无效。

有效解决方案

1. 强制Vite预构建组件库

在vite.config.js中配置optimizeDeps,让Vite提前预构建组件库,避免动态导入时的路径解析问题:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [vue()],
  optimizeDeps: {
    include: ['@arnab7/cheesejs'],
    esbuildOptions: {
      format: 'esm'
    }
  }
});

修改后重启Vite服务,预构建会处理组件库的动态导入逻辑。

2. 关闭Stencil组件的懒加载

修改Stencil项目的stencil.config.ts,禁用懒加载后重新构建发布组件库:

import { Config } from '@stencil/core';

export const config: Config = {
  outputTargets: [
    {
      type: 'dist',
      esmLoaderPath: '../loader',
      lazyLoad: false // 关闭懒加载
    },
    {
      type: 'dist-custom-elements'
    }
  ]
};

更新Vue项目中的组件库依赖后,组件会一次性加载,规避动态导入问题。

3. 直接导入单个组件

如果仅使用部分组件,可绕过Stencil的loader,直接导入对应组件的定义:

// main.js
import { createApp } from 'vue';
import App from './App.vue';
// 直接导入checker-board组件
import '@arnab7/cheesejs/dist/components/checker-board/checker-board';

createApp(App).mount('#app');

此方式无需调用defineCustomElements,组件会自动注册到全局。

4. 配置Vite服务器文件访问权限

若504超时因文件访问限制导致,添加服务器配置允许访问node_modules:

export default defineConfig({
  plugins: [vue()],
  server: {
    fs: {
      allow: ['node_modules']
    }
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:01:29