Maintain src/ folder structure when building to di

2020-07-01 03:17发布

I have a typescript nodejs server with this structure:

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

When using Typescript 2, I was able to transpile my project from the src/ to a dist/ folder and have a mirror image of my directory structure to work with.

With the release of Typescript 3 they have introduced project references and changed the way code is transpiled into an output directory. Now tsc outputs to the dist/ folder in a nested way like this:

dist/
    src/
        middleware/
        utils/
        index.ts

My tsconfig.json is:

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

How can I configure Typescript to output my src/ folder as a mirror image into a dist/ folder?

4条回答
该账号已被封号
2楼-- · 2020-07-01 04:02

The problem appears after adding the resolveJsonModule: true to tsconfig.json

查看更多
The star\"
3楼-- · 2020-07-01 04:04

The structure of the output directory is controlled by the rootDir of the compilerOptions. See documentation here, setting it to ./src should solve the issue.

{
  "compilerOptions": {
    "rootDir": "src",
    ...
  },
  "include": [
    "src/"
  ]
}
查看更多
祖国的老花朵
4楼-- · 2020-07-01 04:07

I had a similar problem when initially converting to a Typescript project. I also set resolveJsonModule: true and the src directory was copied to the output dist directory.

The underlying reason is that one of my source files required package.json at the root of the project. Once i removed that, tsc no longer added src to the dist directory.

In short, make sure you are not requiring files outside of your src directory.

Explanatory FAQ here: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-does---outdir-moves-output-after-adding-a-new-file

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-07-01 04:09

The upgrade from TypeScript 2 to 3 by itself shouldn't have changed the behavior; if we can confirm that it did, that may be a bug. In any case, check that the rootDir compiler option points to your src directory and not to the parent directory, because the structure under the rootDir is what is mirrored under the outDir.

查看更多
登录 后发表回答