使用 Typescript 3 构建到 dist/ 文件夹时保持 src/ 文件夹结构

Maintain src/ folder structure when building to dist/ folder with Typescript 3

我有一个具有这种结构的打字稿 nodejs 服务器:

tsconfig.json
package.json
src/
    middleware/
    utils/
    index.ts
dist/
    middleware/
    utils/
    index.js

当使用 Typescript 2 时,我能够将我的项目从 src/ 转换到 dist/ 文件夹,并有一个我的目录结构的镜像可以使用。

随着 Typescript 3 的发布,他们引入了 project references 并更改了将代码转换为输出目录的方式。现在 tsc 以这样的嵌套方式输出到 dist/ 文件夹:

dist/
    src/
        middleware/
        utils/
        index.js

我的 tsconfig.json 是:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "allowJs": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "declaration": false,
    "outDir": "dist/",
    "lib": [
      "es7",
      "dom"
    ]
  },
  "include": [
    "src/"
  ]
}

如何配置 Typescript 将我的 src/ 文件夹作为镜像输出到 dist/ 文件夹?

从 TypeScript 2 升级到 3 本身不应该改变行为;如果我们可以确认确实如此,那可能是一个错误。在任何情况下,检查 rootDir 编译器选项是否指向您的 src 目录而不是父目录,因为 rootDir 下的结构是 [=13= 下的镜像].

resolveJsonModule: true添加到tsconfig.json后出现问题

我在最初转换为 Typescript 项目时遇到了类似的问题。我还设置了 resolveJsonModule: true 并且 src 目录被复制到输出 dist 目录。

根本原因是我的源文件之一 required package.json 在项目的根目录下。一旦我删除它,tsc 不再将 src 添加到 dist 目录。

简而言之,确保您不需要 src 目录之外的文件。

解释性常见问题解答:https://github.com/Microsoft/TypeScript/wiki/FAQ#why-does---outdir-moves-output-after-adding-a-new-file

输出目录的结构由compilerOptionsrootDir控制。 See documentation here,将其设置为 ./src 应该可以解决问题。

{
  "compilerOptions": {
    "rootDir": "src",
    ...
  },
  "include": [
    "src/"
  ]
}

您可以从 src/entities/Post -> ../entities/Post 文件中更改文件导入 ./来源

这会更改 dist 文件夹中的导入。

除指定compilerOptions.outDir外,在tsconfig.json中指定compilerOptions.rootDir

{
  "compilerOptions": {
     // ...
    "outDir": "dist",
    "rootDir": "./",
    // ...
  }
}

然后运行:$ tsc -btsconfig.json文件所在的文件夹中。

如果您尝试将位于 /scr/mydir/hello.ts 的打字稿文件编译为 /dist/mydir/hello.js,但该文件一直在 /dist/hello.js 处创建,您可以做的是添加另一个打字稿文件在 /src/another.ts。这样,两个编译后的文件将转到 /src/another.js/src/mydir/hello.js。记住,在你的tsconfig.json中,outDir必须设置为./dist

我使用符号link 来完成这个。它巧妙地允许您引用 root-level 个文件而无需直接引用它们。例如:

  1. /src,创建一个link到package.json:
ln -s ../package.json ./details.json
  1. 请参考您的 TypeScript 文件中的 details.json
import { version } from './details.json';

exports.handler = async function ( event: Event ) {
  console.log( `lambda version v${version}` );
  1. 沉浸在 dist 扁平化文件结构的宏伟之中:
$ tsc

$ tree dist 
dist
├── index.d.ts
├── index.js
└── details.json

0 directories, 3 files

如果 include 选项下有多个条目,请确保它们已被解析。

"include": ["src", "tests"],

例如,如果 tests 未找到,src 目录将不会出现在 outDir.