Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

typescript - Setting up tsconfig with spec/test folder

Say I put my code under src and tests under spec:

+ spec
+ --- classA.spec.ts
+ src
+ --- classA.ts
+ --- classB.ts
+ --- index.ts
+ tsconfig.json

I want to only transpile src to the dist folder. Since index.ts is the entry point of my package, my tsconfig.json look like this:

{
  "compileOptions": {
    "module": "commonjs"
    "outDir": "dist"
  },
  "files": {
    "src/index.ts",
    "typings/main.d.ts"
  }
}

However, this tsconfig.json does not include the test files so I could not resolve dependencies in them.

On the other hand, if I include the test files into tsconfig.json then they are also transpiled to dist folder.

How do I solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I ended up defining multiple config files and use extends to simplify them.

Say I have two files: tsconfig.json and tsconfig.build.json

// tsconfig.json
{
  ...
  "exclude": [...]
}

// tsconfig.build.json
{
  ...
  "files": [ "typings/index.d.ts", "src/index.ts" ]
}

This way, I can have fine control on what to build (using tsc -p tsconfig.build.json) and what the ts language service (IDE) handles.

UPDATE: now as my projects grow, I ended up having more config files. I use the "extend" feature that is now available in TypeScript:

// tsconfig.base.json
{
  // your common settings. Mostly "compilerOptions".
  // Do not include "files" and "include" here,
  // let individual config handles that.
  // You can use "exclude" here, but with "include",
  // It's pretty much not necessary.
}

// tsconfig.json
{
  // This is used by `ts language service` and testing.
  // Includes source and test files.
  "extends": "./tsconfig.base.json",
  "atom": { ... },
  "compilerOptions": {
    // I set outDir to place all test build in one place,
    // and avoid accidentally running `tsc` littering test build to my `src` folder.
    "outDir": "out/spec"  
  }
  "include": [ ... ]
}

// tsconfig.commonjs.json or tsconfig.systemjs.json or tsconfig.global.json etc
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    // for some build this does not apply
    "declaration": true/false,
    "outDir": "dist/<cjs, sys, global, etc>",
    "sourceRoot": "..."
  },
  // Only point to typings and the start of your source, e.g. `src/index.ts`
  "files": [ ... ],
  "include": [ ... ]
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...