【问题标题】:Jest+vue: "Cannot find module ....vue"Jest+vue:“找不到模块 ....vue”
【发布时间】:2020-03-23 09:49:10
【问题描述】:

我真的只是想为我的库创建一个 jest+vue 的骨架,并很快得到这个错误。 我知道这个结构不是通常的笑话结构,我在这里尝试描述一个带有辅助控件的测试。

这是我的test 文件夹的内容:arrays.specs.tsarrays.vue

这里是配置:

module.exports = {
  moduleFileExtensions: [
    "js",
    "ts",
    "vue"
  ],
  roots: [
    "<rootDir>/test"
  ],
  testEnvironment: "jest-environment-jsdom",
  testMatch: [
    "**/?(*.)+(spec|test).[tj]s?(x)"
  ],
  transform: {
    ".*\\.(vue)$": "vue-jest",
    ".*\\.(ts)$": "ts-jest"
  },
};

我已经安装了这 3 个包:@vue/test-utilsts-jestvue-jest

现在,有了这个,我在运行 jest 时仍然会出现这个错误:

    test/arrays.spec.ts:4:20 - error TS2307: Cannot find module './arrays.vue'.

    import Arrays from './arrays.vue'

我真的看不出我错过了什么。

【问题讨论】:

  • 这个问题有帮助吗? :github.com/kulshekhar/ts-jest/issues/875
  • 不,我可以导入 ts 模块,只有 Vue 模块会出现问题
  • @eddow - 我想你不记得你是如何解决这个问题的?我似乎也有同样的问题。
  • "moduleNameMapper": { "^@/(.*)$": "&lt;rootDir&gt;/src/$1" } 有帮助吗?

标签: vue.js jestjs


【解决方案1】:

就我而言,问题在于文件shims-vue.d.ts 位于项目的根目录中。我必须将其移至 ./src 才能加载 .vue 模块。

【讨论】:

    【解决方案2】:

    您可能缺少“垫片”文件。把它放在你的“src”目录中:

    shims-vue.d.ts

    declare module '*.vue' {
      import Vue from 'vue';
      export default Vue;
    }
    

    【讨论】:

    • 它适用于普通文件,但对于 .spec.ts 文件它不起作用
    【解决方案3】:

    如果vue jest测试出现Cannot find module issue错误,请设置jest.config.js文件的preset属性如下.

    module.exports = {
      preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
      testEnvironment: 'node'
    }
    

    【讨论】:

      【解决方案4】:

      npm 包vue-jest 正在使用'babel-core'。如果您从 node_modules -&gt; \node_modules\vue-jest\lib\compilers\babel-compiler.js 打开文件,您将看到下面的代码。

      const babel = require('babel-core')
      const loadBabelConfig = require('../load-babel-config.js')
      
      module.exports = function compileBabel (scriptContent, inputSourceMap, inlineConfig, vueJestConfig, filePath) {
        ...
      

      第一个常量是导入 npm 包babel-core

      如果你用@babel/core 改变它,你的问题应该得到解决。 修改后应该是这样的:

      const babel = require('@babel/core')
      const loadBabelConfig = require('../load-babel-config.js')
      
          module.exports = function compileBabel (scriptContent, inputSourceMap, inlineConfig, vueJestConfig, filePath) {
            ...`
      

      我在网上看到过他们建议用 babe-core(7.0.0.0-bridge) 替换 babel-core(版本 6.)的解决方案。就我而言,它破坏了我的解决方案,我无法再发布,但 jest 在 npm 上运行良好。 对于已经设置了 webpack.config.js 并且他们也有 .babelrc 的人来说,这是一个解决方案。

      安装 @babel/core : npm install --save-dev @babel/core babel-core 是 babel 的第 6 版,@babel/core 是 babel 的第 7 版。

      【讨论】:

      • 好吧,我出于好奇尝试过,但无济于事。此外,我总是认为修改node_modules 下的文件是非常糟糕的做法
      猜你喜欢
      • 1970-01-01
      • 2021-03-15
      • 2020-09-27
      • 2020-08-30
      • 2019-07-07
      • 2020-01-29
      • 2019-06-12
      • 2021-11-13
      • 2022-08-13
      相关资源
      最近更新 更多