TypeScript - 将文件导入并编译成一个文件

3

我是 TypeScript 的新手,我的 api 命名空间中有一个函数,位于 api.ts 文件中,用于连接到我的 api:

namespace api
{
    export function connect() : boolean
    {
        return false;
    }
}

这是我test.ts文件的内容。
///<reference path="api.ts"/>
api.connect();

使用TypeScript编译后会生成两个文件:api.jstest.js。是否可以将其编译为一个名为test.js的文件,但将otherPage.ts编译为单独的包?

注意:

这是我的文件结构:

- test.ts
- api.ts
- otherPage.ts

这是期望的输出:
- test.js (api.ts and test.ts compiled into one file)
- otherPage.js

这是我用于自动编译文件的命令:tsc --watch。我希望有一种解决方案,可以避免我针对要包含的文件更改此命令。
我在多个文件中使用api.ts,因此创建一个ts文件对我来说不是一个选项。 临时解决方案: 作为临时解决方案,我将api.ts包含在所有文件中。这对我来说不是大问题,因为我在将TypeScript编译为JavaScript后,使用Google Closure Compiler编译JavaScript文件。
我使用Visual Studio Code,所以我可以在我的tasks.json中自动化此过程:
{
    "version": "0.1.0",
    "command": "tsc",
    "showOutput": "silent",
    "windows": {
        "command": "tsc.cmd"
    },
    "args": 
    [
        "res/ts/modules/api.ts",
        "${file}",
        "--outFile", "res/js/${fileBasenameNoExtension}.js",
        "--listFiles", "true"
    ],
    "problemMatcher": "$tsc"
}

按下 ctrl + b 来执行它。


为什么不创建一个 TS 文件? - Alexey Obukhov
@AlexeyObukhov 我在多个文件中使用 api.ts - user7353781
2个回答

1

你需要在 tsconfig.json 中使用 --outFile 选项:

  "compilerOptions": {
      "outFile": "dist/output.js"
  }

或者像这样将其传递给编译器:
tsc test.ts --outFile dist/output.js

这将所有文件编译成一个文件,包括 otherPage.ts。我只想将 test.tsapi.ts 编译成一个文件。 - user7353781
我认为仅使用tsc是不可能实现的。你可以使用不同的文件集多次运行tsc,但这并不是一个理想的解决方案。需要使用模块打包工具来实现。 - Max Koretskyi
你考虑使用webpack吗? - Max Koretskyi
webpack是一个打包系统,了解一下。如果您考虑使用它,我可以为您提供一个解决方案。 - Max Koretskyi

0

你可以使用webpack、gulp等工具打包你的源代码。 https://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html

按照上面文档链接中的教程,你可以创建一个目录,例如my-app, 然后在这个目录下运行

npm init

然后运行

npm install -g gulp

npm install gulp gulp-typescript --save-dev

创建src目录和gulpfile.js文件,在gulpfile.js文件中粘贴以下代码:

var gulp = require("gulp"); var ts = require("gulp-typescript");

gulp.task("default", function () {
    var tsResult = gulp.src("src/*.ts")
        .pipe(ts({
              noImplicitAny: true,
              out: "output.js"
        }));
    return tsResult.js.pipe(gulp.dest("built/local"));
});

将您的ts源代码放在src文件夹中,然后在命令行中运行gulp命令,例如在终端或Windows上的CMD


请问您能否提供我更多的信息?我对webpack、gulp等不太熟悉。 - user7353781
使用这个解决方案,otherPage.ts会被排除在output.js之外吗? - user7353781
请在此处阅读有关gulp-typescript的更多信息:https://github.com/ivogabe/gulp-typescript - Tiep Phan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接