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

LeetCode本地TS项目:如何配置让import与namespace正常工作?

解决方案

1. 修正tsconfig.json配置

确保你的tsconfig.json包含以下关键配置项,适配ES模块解析规则:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "rootDir": "./tasks",
    "outDir": "./dist",
    "strict": true,
    "resolveJsonModule": true
  },
  "include": ["tasks/**/*"],
  "exclude": ["node_modules"]
}
  • module: ESNext:启用ES模块语法支持
  • moduleResolution: NodeNext:让TypeScript遵循Node.js的ES模块路径解析逻辑
  • rootDir/include:明确指定源码目录,避免编译范围混乱

2. 修正导入路径写法

ES模块要求导入必须指定完整文件扩展名,修改226_import.ts中的导入语句:

// 错误写法(省略扩展名)
// import { TreeNode } from '../common/TreeNode';

// 正确写法(添加.ts扩展名)
import { TreeNode } from '../common/TreeNode.ts';

3. 调整ts-node运行命令

启用"type": "module"后,ts-node需要显式开启ES模块模式,修改运行命令为:

px ts-node --esm ./tasks/import/226_import.ts

也可以在package.json的scripts中添加快捷命令,简化操作:

{
  "scripts": {
    "leetcode:226": "ts-node --esm ./tasks/import/226_import.ts"
  }
}

之后直接运行npm run leetcode:226即可执行代码。

4. 结合Namespace避免变量冲突

如果要通过Namespace隔离代码、避免变量名重复,修改common/TreeNode.ts的结构:

export namespace LeetCodeCommon {
  export class TreeNode {
    val: number;
    left: TreeNode | null;
    right: TreeNode | null;
    constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
      this.val = val ?? 0;
      this.left = left ?? null;
      this.right = right ?? null;
    }
  }
}

在226_import.ts中导入并使用:

import { LeetCodeCommon } from '../common/TreeNode.ts';

// 通过Namespace访问TreeNode,避免全局变量冲突
const root = new LeetCodeCommon.TreeNode(1);

5. 额外排错步骤

  • 确认package.json的"type": "module"位于顶层,没有嵌套在其他字段中
  • 更新ts-node和typescript到最新版本:npm install -D ts-node@latest typescript@latest
  • 检查所有相对导入路径的层级是否正确(比如../common对应tasks目录下的common文件夹)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:47:38