如何将 Node.js 的 TypeScript 代码编译为一个文件? [英] How do I compile my TypeScript code for Node.js to one file?

查看:40
本文介绍了如何将 Node.js 的 TypeScript 代码编译为一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to compile TypeScript to one file when using with Node.js.

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

I have tried configuring "tsconfig.json" like this:

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

...但是当我尝试将 module" 设置为 "commonjs"` 时,出现错误:

...but when I try with module" set to"commonjs"`, I get the error:

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

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

If I change it to "module": "system", I get this error when running the file in node:

ReferenceError: System is not defined

如果我将 module 更改为 "amd",在 node 中运行文件时会出现此错误:

If I change module to "amd", I get this error when running the file in node:

ReferenceError: define is not defined

推荐答案

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

It is not possible to bundle Node.js modules into a single file with the TypeScript compiler alone: each file in the CommonJS module system (used by Node.js) is treated as a single module, and cannot be joined together without proper module bundling techniques found in the many JavaScript code bundlers out there (such as Browserify, Webpack, Rollup, Parceljs, ...).

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

Other module systems such as SystemJS do not have this limitation, and module definitions can be concatenated into a single file using just the TypeScript compiler: tsc ... --outfile bundle.js -module system. However, they are not supported by Node.js on the fly.

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

For the actual solution, there are two reasonable choices: either configure your project to bundle the solution using a separate tool (Browserify, Webpack, ...), or include an implementation of SystemJS into your Node.js application (instructions here).

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

I will also end with a side note: consider evaluating whether you really need to bundle your server-sided code. Bundling is typically performed in frontend projects to reduce the size of client-sided resources, although it can be done as well for server applications in resource-efficient scenarios.

这篇关于如何将 Node.js 的 TypeScript 代码编译为一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆