【问题标题】:karma-typescript cannot find module业力打字稿找不到模块
【发布时间】:2017-08-26 22:50:18
【问题描述】:

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

错误:

错误 [compiler.karma-typescript]: src/drawing/canvas.model.ts(1,23): 错误 TS2307:找不到模块 'utils'。

错误 [compiler.karma-typescript]: src/models/grid.model.ts(1,23): 错误 TS2307: 找不到模块 'utils'。

错误 [compiler.karma-typescript]: src/utils/specs/obj.utils.spec.ts(1,23): 错误 TS2307: 找不到 模块'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 天的文档,试图让这些简单的单元测试运行,但无济于事。至少我的路径结构不是这样。任何帮助将不胜感激!


更新: 我尝试将我本地安装的 Typescript 更新为 2.2.2,以匹配同样是 2.2.2 的 Karma-Typescript 版本。同样的错误,同样的场景——我的本地版本编译得很好,但 Karma-Typescript 版本不支持。

【问题讨论】:

    标签: javascript typescript karma-runner


    【解决方案1】:

    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 版本:)

    【讨论】:

    • 谢谢!!那解决了它。 :)
    • 我想知道“karma.conf.js”中的“module”是否也可以设置为“es6”以使其与“tsconfig.json”保持一致。
    • @user130685 从技术上讲,Karma 可以测试 es6 模块代码(即,使用 <script type="module> 标记将代码注入运行器)但是你有一个不同的问题:非相对导入中断。大多数编写 ES6 代码的人都使用 Node 样式的导入并让打包器为您解析它们,但 Karma 不会这样做(至少是开箱即用的)。
    【解决方案2】:

    由于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 是解决问题的关键。

    【讨论】:

    • +1 指出您可以将karma-typescript 直接指向tsconfig.json,而不是在两个地方都复制一堆选项。
    猜你喜欢
    • 2021-01-07
    • 2013-12-30
    • 2018-06-27
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多