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

使用TypeScript --outFile编译时提示System is not defined的原因咨询

解决TypeScript使用--outFile时出现“System is not defined”的问题

这个错误的核心原因很明确:当你使用--outFile编译TypeScript代码时,TypeScript仅支持将AMD或System模块打包成单个文件(全局代码除外)。如果你的tsconfig.json里module选项设为了system,但运行环境中没有引入SystemJS模块加载器,就会出现System is not defined的报错。

下面是具体的解决方案,你可以根据自己的场景选择:

1. 如果你确实需要使用System模块系统

如果你的项目依赖System模块,那必须在运行环境中引入SystemJS库:

  • 在浏览器环境中,在加载你的打包文件之前,先引入SystemJS:
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/6.14.0/system.min.js"></script>
    <script>
      // 加载你的打包文件
      System.import('./dist/bundle.js');
    </script>
    
  • 确保你的tsconfig.json配置正确:
    {
      "compilerOptions": {
        "module": "system",
        "outFile": "./dist/bundle.js",
        "target": "ES5" // 或你需要的目标版本
      }
    }
    

2. 改用AMD模块系统(更常用的浏览器打包方案)

如果不需要System模块,你可以将模块系统切换为AMD,搭配RequireJS使用:

  • 修改tsconfig.json:
    {
      "compilerOptions": {
        "module": "amd",
        "outFile": "./dist/bundle.js",
        "target": "ES5"
      }
    }
    
  • 在浏览器中引入RequireJS并加载你的打包文件:
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" data-main="./dist/bundle.js"></script>
    

3. 如果你不需要模块系统(全局代码场景)

如果你的代码都是全局变量,没有使用import/export,可以直接禁用模块系统:

  • 修改tsconfig.json:
    {
      "compilerOptions": {
        "module": "none",
        "outFile": "./dist/bundle.js",
        "target": "ES5"
      }
    }
    
  • 直接在HTML中引入打包后的文件即可,不需要任何模块加载器:
    <script src="./dist/bundle.js"></script>
    

额外提示:Node.js环境不适合用--outFile

如果是Node.js项目,TypeScript的--outFile不支持CommonJS模块(Node默认的模块系统)的打包。这种情况下,建议使用Webpack、Rollup或ESBuild这类专门的打包工具,它们能更好地处理Node环境的模块打包需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:04:26