如何将Node.js的TypeScript代码编译为一个文件?

use*_*582 14 node.js typescript typescript2.0

我想在使用Node.js时将TypeScript编译为一个文件.

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

"compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "noImplicitAny": false,
    "sourceMap": false,
    "outFile": "./app/index.js",
    "pretty": true,
    "types": [
      "node"
    ]
  }",
Run Code Online (Sandbox Code Playgroud)

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

error TS6082: Only 'amd' and 'system' modules are supported alongside --outFile.
Run Code Online (Sandbox Code Playgroud)

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

ReferenceError: System is not defined
Run Code Online (Sandbox Code Playgroud)

如果我module改为"amd",我在运行文件时遇到此错误node:

ReferenceError: define is not defined
Run Code Online (Sandbox Code Playgroud)

E_n*_*ate 21

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

其他模块系统(如SystemJS)没有此限制,只需使用TypeScript编译器就可以将模块定义连接成单个文件:tsc ... --outfile bundle.js -module system.但是,Node.js不支持它们.

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

我还将以旁注结束:捆绑服务器端代码几乎没有任何好处.捆绑通常在前端项目中执行,以减少客户端资源的大小.


Tom*_*Tom 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
Run Code Online (Sandbox Code Playgroud)

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
};
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./",
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)