Karma,Typescript定义文件未加载

ant*_*kas 10 typescript karma-runner tsconfig webpack

我正在使用karma,webpack和typescript设置开发环境,但我遇到的问题是karma没有在测试中应用自定义定义文件.

这是我的项目文件结构:

// file structure
project/
    config/
        karma.conf.js
    tests/
        test-files.ts 
        ...        
    src/
        tsdefinitions.d.ts
        other-ts-files.ts
        ...
    tsconfig.json
Run Code Online (Sandbox Code Playgroud)

这里是与webpack和typescript相关的karma配置部分

webpack: {
  devtool: 'eval-source-map',
  resolve: {
    extensions: ['.webpack.js', '.web.js', '.ts', '.tsx', '.js']
  },
  module: {
    loaders: [{
      test: /\.tsx?$/,
      loader: 'awesome-typescript-loader'
    }]
  }
},
webpackMiddleware: {stats: 'errors-only'},
mime: {'text/x-typescript': ['ts','tsx']},
basePath: '../',
files: [{
  pattern: './test/**/*.ts',
  watched: false
}],
preprocessors: {
  './test/**/*.ts': ['webpack', 'sourcemap']
}
Run Code Online (Sandbox Code Playgroud)

最后是tsconfig.json

{
  "compilerOptions": {
    "removeComments": true,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "./",
    "sourceMap": true,
    "noImplicitAny": true,
    "allowJs": true,
    "module": "commonjs",
    "target": "es2015",
    "paths": {
      "jquery": ["node_modules/jquery/dist/jquery"]
    },
    "exclude": ["node_modules"],
    "files": [
      "src/**/*.ts"
    ]
  },
  "awesomeTypescriptLoaderOptions": {
    "useCache": false,
    "useBabel": true,
    "babelOptions": {
      "presets": [
        "es2015",
        "stage-0"
      ]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在进行像这样的业力测试

./node_modules/.bin/karma start ./config/karma.conf.js
Run Code Online (Sandbox Code Playgroud)

现在,当我只使用karma构建项目文件时,一切正常,它们构建时没有错误.

但是当我运行测试构建时,在tsdefinitions.d.ts文件中声明了很多缺少Window接口属性的错误.

Gor*_*ett 2

我已经能够通过将我的类型放在与源文件不同的文件夹中并将其包含在tsconfig.jsonusingtypeRoots字段中来实现此目的。

我的tsconfig.json

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "./@types"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/**/*.test.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

karma.config.js:

{
  "compilerOptions": {
    ...
    "typeRoots": [
      "./@types"
    ]
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "src/**/*.test.ts"
  ]
}
Run Code Online (Sandbox Code Playgroud)

现在我可以为没有任何类型的模块定义类型,如下所示
@types/universal-url/index.d.ts

declare module 'universal-url' {
  export {URL, URLSearchParams} from 'whatwg-url' 

  export function shim(): void
}
Run Code Online (Sandbox Code Playgroud)

还有我的src/utils/parseUrl.ts文件:

import { URL } from 'universal-url'

export function parseUrl(url: string) {
  return new URL(url)
}

Run Code Online (Sandbox Code Playgroud)

同样,关键是 的 typeRoots 字段tsconfig.json。这是文档: https: //www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types