26

与 Node.js 一起使用时,我想将 TypeScript 编译为一个文件。

我试过像这样配置“tsconfig.json”:

"compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "noImplicitAny": false,
    "sourceMap": false,
    "outFile": "./app/index.js",
    "pretty": true,
    "types": [
      "node"
    ]
  }",

...但是当我尝试使用module" set to“commonjs”`时,我得到了错误:

error TS6082: Only 'amd' and 'system' modules are supported alongside --outFile.

如果我将其更改为"module": "system",则在以下位置运行文件时会出现此错误node

ReferenceError: System is not defined

如果我更改module"amd",则在以下位置运行文件时会出现此错误node

ReferenceError: define is not defined
4

2 回答 2

32

仅使用 TypeScript 编译器无法将 Node.js 模块捆绑到单个文件中:CommonJS 模块系统(由 Node.js 使用)中的每个文件都被视为单个模块,如果没有适当的模块捆绑,则无法将它们连接在一起在许多 JavaScript 代码捆绑器中发现的技术(例如 Browserify、Webpack、Rollup、Parceljs 等)。

其他模块系统(例如 SystemJS)没有此限制,并且可以仅使用 TypeScript 编译器将模块定义连接到单个文件中:tsc ... --outfile bundle.js -module system. 但是,Node.js 不即时支持它们。

对于实际的解决方案,有两个合理的选择:或者将您的项目配置为使用单独的工具(Browserify、Webpack、...)捆绑解决方案,或者将SystemJS的实现包含到您的 Node.js 应用程序中(此处的说明)。

我还将以附注结束:考虑评估您是否真的需要捆绑服务器端代码。捆绑通常在前端项目中执行以减少客户端资源的大小,尽管在资源高效的场景中也可以为服务器应用程序执行捆绑。

于 2016-10-13T14:09:57.397 回答
9

@E_net4是对的。目前,仅使用 TypeScript 编译器无法将模块构建到单个文件中。本文描述了如何使用 webpack 执行此操作,其中文件结构为:

├── index.js
├── package.json
├── src
│   ├── add-message
│   │   └── index.ts
│   ├── index.ts
│   └── upcase-messages
│       └── index.ts
├── tsconfig.json
└── webpack.config.js

webpack.config.js

const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: './src/index.ts',
    output: {
        filename: 'index.js', // <-- Important
        libraryTarget: 'this' // <-- Important
    },
    target: 'node', // <-- Important
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                loader: 'ts-loader',
                options: {
                    transpileOnly: true
                }
            }
        ]
    },
    resolve: {
        extensions: [ '.ts', '.tsx', '.js' ]
    },
    externals: [nodeExternals()] // <-- Important
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./",
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
于 2019-05-20T11:44:49.100 回答