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

如何优化Python修改tsconfig.json动态内容的冗余代码?

优化方案

1. 消除重复配置

把node和react共用的编译选项抽成公共配置,再针对不同插件补充差异配置,用字典的update()方法合并,避免大量重复代码:

import json

def update_tsconfig(directory, plugin):
    # 定义公共编译选项
    base_compiler_options = {
        "strict": True,
        "alwaysStrict": True,
        "noImplicitAny": True,
        "noImplicitThis": True,
        "strictNullChecks": True,
        "strictBindCallApply": True,
        "strictFunctionTypes": True,
        "strictPropertyInitialization": True,
        "useUnknownInCatchVariables": True,
        "noUnusedLocals": True,
        "noUnusedParameters": True,
        "allowUnusedLabels": True,
        "allowUnreachableCode": True,
        "noImplicitOverride": True,
        "noImplicitReturns": True,
        "noUncheckedIndexedAccess": True,
        "noPropertyAccessFromIndexSignature": True,
        "noFallthroughCasesInSwitch": True,
        "exactOptionalPropertyTypes": True,
        "forceConsistentCasingInFileNames": True
    }

    # 不同插件的差异配置
    plugin_specific = {}
    if plugin == "node":
        plugin_specific = {"module": "commonjs"}
    elif plugin == "react":
        plugin_specific = {
            "jsx": "react-jsx",
            "allowJs": False,
            "esModuleInterop": False,
            "allowSyntheticDefaultImports": True
        }

    # 合并配置:差异配置会覆盖公共配置里的同名项(如果有的话)
    compiler_options = base_compiler_options.copy()
    compiler_options.update(plugin_specific)

    # 读写tsconfig.json
    tsconfig_path = f"{directory}/tsconfig.json"
    with open(tsconfig_path, 'r+') as file:
        file_data = json.load(file)
        file_data["compilerOptions"] = compiler_options
        file.seek(0)
        json.dump(file_data, file, indent=2)
        file.truncate()  # 防止原文件内容比新内容长,残留多余字符

2. 处理单个参数的添加/修改

单独写一个函数,用来快速添加或修改某个编译选项,不管该选项是否已存在:

def update_single_tsconfig_option(directory, option_name, value):
    tsconfig_path = f"{directory}/tsconfig.json"
    with open(tsconfig_path, 'r+') as file:
        file_data = json.load(file)
        # 确保compilerOptions键存在,避免KeyError
        if "compilerOptions" not in file_data:
            file_data["compilerOptions"] = {}
        file_data["compilerOptions"][option_name] = value
        file.seek(0)
        json.dump(file_data, file, indent=2)
        file.truncate()

# 使用示例:添加或修改noUncheckedIndexedAccess为False
update_single_tsconfig_option("./my-project", "noUncheckedIndexedAccess", False)

优化点说明

  • 抽离公共配置后,后续修改公共选项只需改一处,减少维护成本
  • 用update()合并配置,逻辑清晰,代码简洁
  • 添加file.truncate(),避免原文件内容长度大于新内容时,末尾残留垃圾字符
  • 单个参数处理函数做了容错,即使tsconfig里没有compilerOptions键也不会报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:17:43