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

如何在遗留JavaScript文件中使用TypeScript类的常量?

在遗留JavaScript文件中使用TypeScript类的简单示例

步骤1:配置TypeScript编译参数

创建tsconfig.json文件,确保编译后的代码能被JavaScript兼容读取:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "outDir": "./dist",
    "declaration": false
  },
  "include": ["./src/**/*"]
}

步骤2:编写TypeScript常量类

在src/constants.ts中写入你定义的类:

export class ExampleConstantsClass {
  static readonly exampleConst = 1;
}

步骤3:编译TypeScript代码

在终端运行编译命令,生成可被JS调用的文件:

tsc

编译完成后,dist/constants.js会生成对应的JavaScript代码。

步骤4:在遗留JavaScript文件中调用

假设你的JS文件是legacy.js,通过require导入编译后的模块,然后使用:

const { ExampleConstantsClass } = require('./dist/constants');

function exampleFunction() {
  return ExampleConstantsClass.exampleConst;
}

// 测试调用
console.log(exampleFunction()); // 输出 1

如果你的项目支持ES模块(比如浏览器环境或配置了package.json的"type": "module"),可以用ES导入语法:

import { ExampleConstantsClass } from './dist/constants.js';

function exampleFunction() {
  return ExampleConstantsClass.exampleConst;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:40:42