业力打字稿找不到模块

karma-typescript cannot find module

我有一个非常小的项目,我正在尝试为其设置单元测试。项目 在直接使用 tsc 时编译得很好 ,但是,我在尝试执行使用 karma-typescript 框架的测试时遇到以下 Typescript 编译错误:

错误:

ERROR [compiler.karma-typescript]: src/drawing/canvas.model.ts(1,23): error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/models/grid.model.ts(1,23): error TS2307: Cannot find module 'utils'.

ERROR [compiler.karma-typescript]: src/utils/specs/obj.utils.spec.ts(1,23): error TS2307: Cannot find module 'utils'.


项目结构: 我已经建立了一个结构如下的项目:

|-dist/
|-node_modules/
|-src/
| |
| |-drawing/
| | |
| | |-canvas.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| |
| |-models/
| | |
| | |-grid.model.ts
| |    ________________________________
| |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| |    --------------------------------
| | 
| |-utils/
| | |
| | |-index.ts
| | |  _________________________
| | | | export module Utils {}  |
| | |  -------------------------
| | |
| | |-specs/
| | | |
| | | |-obj.utils.spec.ts
| | |    ________________________________
| | |   | import { Utils } from 'utils'; |  Karma Fails (tsc is fine)
| | |    --------------------------------
| | |
|-karma.config.js
|-tsconfig.json
|-package.json

我很清楚我的 tsconfig.json 文件和 karma-typescript 内部使用的编译器设置之间存在差异。以下是我对这两个文件进行结构化处理的方式。根据 documentation for karma-typescript,我可以在我的 karma.conf 文件中配置几个选项,告诉 karma-typescript 尊重我在我的 Typescript 配置文件中的设置,即 "paths" 属性,这是我指定 Typescript 在哪里寻找我的 utils 模块的地方。

KARMA.CONF.JS

// Karma configuration
// Generated on Fri Mar 31 2017 16:42:11 GMT-0700 (PDT)
module.exports = function(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',
    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine', 'karma-typescript'],
    // Plugins
    plugins: [
      'karma-spec-reporter',
      'karma-jasmine',
      'karma-chrome-launcher',
      'karma-jasmine-html-reporter',
      'karma-typescript'
    ],
    // list of files / patterns to load in the browser
    files: [{
      pattern: "./src/**/*.ts"
    }],
    // list of files to exclude
    exclude: ['**/*.spec.js'],

    // Karma Typescript compiler options
    karmaTypescriptConfig: {
      bundlerOptions: {
        resolve: {
          directories: ["src", "node_modules", "src/utils"]
        }
      }
    },
    compilerOptions: {
      module: 'commonjs',
      moduleResolution: 'node',
      paths: {
        'utils': ['./src/utils'], 'utils/*': ['./src/utils/*']
      }
    },
    tsconfig: './tsconfig.json',


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      "**/*.ts": ["karma-typescript"]
    },
    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'kjhtml', 'spec', "karma-typescript"],
    // web server port
    port: 9876,
    // enable / disable colors in the output (reporters and logs)
    colors: true,
    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,
    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,
    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}


这是我的 Typescript 配置文件。请注意,我在 tsconfig 文件的 "paths" 部分注册了 "utils",这有助于 Typescript 编译器的 module resolution process。这适用于正常的 Typescript 编译,但这可能是因为我的 Typescript 编译器实际上尊重我的 tsconfig 文件中的设置。我正在使用 Typescript 2.0.10。但似乎 karma-typescript 使用的是 Typescript 2.2.2,这可能是错误的潜在来源。我将不得不 运行 我的编译器针对那个版本,看看我是否能产生同样的错误。

TSCONFIG.JSON

{
  "compileOnSave": true,
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "./dist",
    "paths": {
      "utils/*": ["./src/utils/*"],
      "utils": ["./src/utils"]
    },
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": ["es5", "dom"],
    "mapRoot": "./",
    "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5",
    "rootDirs": ["./dist", "."]
  },
  "exclude": ["./node_modules", "./dist", "**/*.d.ts"],
  "include": ["./src/**/*.ts"]
}

谁能帮我解决这个问题?我对 Typescript 很满意,但对 Karma 还很陌生。我已经搜索了大约 2 天的文档,试图获得这些简单的单元测试 运行ning,但无济于事。至少我的路径结构不是这样。任何帮助将不胜感激!


更新: 我尝试将本地安装的 Typescript 更新为 2.2.2,以匹配同样为 2.2.2 的 Karma-Typescript 版本。同样的错误,同样的场景 - 我的本地版本编译正常,但 Karma-Typescript 版本不成功。

Karma 配置中有一个小错误,compilerOptionstsconfig 属性应该在 karmaTypescriptConfig 属性.

鉴于您的项目结构示例,这里是 tsckarma-typescript 的最小工作配置示例:

Karma.conf.js

module.exports = function(config) {
    config.set({

        frameworks: ["jasmine", "karma-typescript"],

        files: [
            { pattern: "src/**/*.ts" }
        ],

        karmaTypescriptConfig: {
            compilerOptions: {
                module: "commonjs"
            },
            tsconfig: "./tsconfig.json",
        },

        preprocessors: {
            "**/*.ts": ["karma-typescript"]
        },

        reporters: ["progress", "kjhtml", "spec", "karma-typescript"],

        browsers: ["Chrome"]
    });
};

tsconfig.json

{
    "compileOnSave": true,
    "compilerOptions": {
        "baseUrl": ".",
        "outDir": "./dist",
        "paths": {
            "utils/*": ["./src/utils/*"],
            "utils": ["./src/utils"]
        },
        "module": "es6",
        "moduleResolution": "node",
        "sourceMap": true,
        "target": "es5"
    }
}

我使用 typescript@2.2.2karma-typescript@3.0.0 进行了测试。

此外,请注意 karma-typescript 仅将 Typescript 作为开发依赖项,让您可以使用 1.6.2 及更高版本的任何 Typescript :)

由于 tsconfig.json 中的自定义模块路径,我遇到了错误 Error: Unable to resolve module [...] from [...]。这是我针对该问题的解决方案:

// tsconfig.json
"compilerOptions" {
    ...
    "paths": { // My custom module path
        "parchment/blot/*": ["node_modules/parchment/dist/src/blot/*"],
        "parchment/attributor/*": ["node_modules/parchment/dist/src/attributor/*"]
    },
    ...


// karma.conf.js
...
karmaTypescriptConfig: {
    tsconfig: './tsconfig.json',
    bundlerOptions: {
        resolve: {
            alias: {
                'parchment/dist/src/attributor': './node_modules/parchment/dist/parchment.js',
                'parchment/dist/src/blot/abstract': './node_modules/parchment/dist/parchment.js'
            },
            extensions: ['.js'] // Extension that causes the error
        }
    }
}
...

如您所见,bundlerOptions.resolve 是解决问题的关键。