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

使用映射路径导入dist模块时TypeScript Web组件继承失效

TypeScript路径映射导致Web组件继承类型错误问题

我在编译TypeScript生成JS代码并打包的过程中,遇到了Web组件继承相关的问题:使用tsconfig中配置的paths映射路径导入父组件时,子组件无法识别继承关系;改用相对路径导入则完全正常。

tsconfig.json配置

{
  "compilerOptions": {
    "target": "es2017",
    "moduleResolution": "node",
    "sourceMap": true,
    "baseUrl": "./public",
    "outDir": "dist",
    "paths": {
      "@js/*": ["../dist/public/javascripts/*"]
    }
  }
}

父组件代码(Parent.ts)

const template = document.createElement('template');
template.innerHTML = `
    <style>
    </style>
    <h1>Parent</h1>
`;

export class Parent extends HTMLElement {
    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
}

window.customElements.define('my-parent', Parent);

子组件代码(Child.ts)

// 错误导入方式:使用路径映射,会触发类型报错
// import { Parent } from '@js/Parent.js';

// 正确导入方式:使用相对路径,可正常运行
import { Parent } from './Parent.js';

const template = document.createElement('template');
template.innerHTML = `
    <style>
    </style>
    <h1>Child</h1>
`;

class Child extends Parent {
    formId = 'adventureNpcs';

    constructor() {
        super();
        this.attachShadow({ mode: 'open' });
        this.shadowRoot.appendChild(template.content.cloneNode(true));
    }
}

window.customElements.define('my-child', Child);

报错信息

使用@js/Parent.js映射路径导入时,TypeScript会抛出以下类型错误:

Property 'attachShadow' does not exist on type 'Child'.

疑问

为什么相对路径导入能正常识别Parent的继承关系,而使用@js映射路径就会出现类型错误?是否遗漏了某些配置步骤,或者路径映射的配置存在问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:25:18