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

如何将module声明包裹的TypeScript类正确引入Angular项目

问题原因

你生成的代码使用了TypeScript 旧式命名空间语法(module关键字定义的内部模块),而Angular 基于ES 标准模块体系开发,二者模块机制不兼容,因此会出现引用失败的问题。

解决方案

方案一:修改Typewriter生成模板输出ES模块(推荐)

这是适配Angular 生态的最优方案,直接调整你的Typewriter 模板文件,移除命名空间包裹逻辑,改为直接在文件顶层导出类。
修改后生成的文件(示例文件名为user.model.ts)内容如下:

export class User {
    // ID
    public id: string = null;
    // FIRSTNAME
    public firstName: string = null;
    // LASTNAME
    public lastName: string = null;
    // EMAIL
    public email: string = null;
}

之后在需要引用的文件中直接按ES模块语法导入即可:

// 路径替换为该文件在你项目中的相对路径
import { User } from './models/user.model';

方案二:兼容现有命名空间代码(临时过渡用)

如果暂时不需要调整生成模板,可按以下步骤处理现有代码:

  1. 将生成的TS文件放入Angular项目src/app下的自定义目录(例如src/app/generated-models)
  2. 检查项目根目录tsconfig.json,确认compilerOptions下已开启以下配置:
{
  "compilerOptions": {
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}
  1. 在需要引用的文件中按如下方式导入使用:
import * as Budget from './generated-models/你的生成文件名';
const user = new Budget.Infrastructure.Model.User();

如果仍提示命名空间无法识别,可在生成的TS文件末尾添加一行导出代码:

export = Budget.Infrastructure.Model;

之后简化导入逻辑:

import * as Model from './generated-models/你的生成文件名';
const user: Model.User = new Model.User();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:27:05