How do I fix "ReferenceError: System is not defined" when running script from command line?

How do I fix "ReferenceError: System is not defined" when running script from command line?

我正在尝试创建 typescript 服务器端(示例代码 import mongoose from 'mongoose'; )并且我知道我应该在之前初始化 systemjs,但我不知道如何在服务器端脚本中进行。

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

如果您想在服务器端使用模块 'system' - 您必须安装 systemjs 包并进行配置:

import System = require('systemjs');

System.config({
  ...
});

System.import(...);

但在我看来,最好在 node.js 中以 运行 和 运行 为目标,而不需要任何额外的依赖项。

作为奖励 - 您还可以 运行 在浏览器中使用 systemjs 作为加载器的 commonjs 模块 - 它支持开箱即用地加载它们。

[编辑]

请注意,node.js 是使用 commonjs 作为模块标准构建的。因此,您可以使用 SystemJS 使用 'system' 模块,但只有 'inside' 您的主程序必须采用 commonjs 格式才能在 nodejs 中使用 运行。

我通过将 "module" : "commonjs" 放在 tsconfig.json 中来解决这个问题。 Commonjs是历史悠久的节点模块系统。