微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在反应项目中为笑话设置绝对路径

如何解决在反应项目中为笑话设置绝对路径

我遵循了 this document 并在整个项目中设置了绝对路径。但是当我运行测试用例时,它给了我以下错误

  Your application tried to access assets,but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

required package: assets (via "assets\icons")
required by: E:\Project\src\components\LayoutContainer\


Require stack:
  src/components/LayoutContainer/index.jsx
  src/components/LayoutContainer/__test__/index.spec.js

  27286 |     enumerable: false
  27287 |   };
> 27288 |   return Object.defineProperties(new Error(message),{
        |                                  ^
  27289 |     code: { ...propertySpec,27290 |       value: code
  27291 |     },at internalTools_makeError (.pnp.js:27288:34)
  at resolvetoUnqualified (.pnp.js:28247:23)
  at resolveRequest (.pnp.js:28345:29)
  at Object.resolveRequest (.pnp.js:28423:26)

我用于 jest 配置的 Package.json 如下

 "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}","!src/components/**/*.{js,"!<rootDir>/node_modules/","!<rootDir>/path/to/dir/","!src/**/*.css","!src/setUpTests.js","!src/index.jsx"
    ],"coverageThreshold": {
      "global": {
        "branches": 90,"functions": 90,"lines": 90,"statements": 90
      }
    },"snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },

我尝试遵循许多 open 解决方案。但没有一个我有

我的 jsonconfig.json 文件

{
  "compilerOptions": {
    "baseUrl": "src"
  },"include": ["src"]
}

解决方法

我添加了以下配置作为 craco 文件的一部分并为我工作

module.exports = {
  jest: {
    configure: {
      moduleNameMapper: {
        // Jest module mapper which will detect our absolute imports.
        '^assets(.*)$': '<rootDir>/src/assets$1','^pages(.*)$': '<rootDir>/src/pages$1','^config(.*)$': '<rootDir>/src/config$1','^navigation(.*)$': '<rootDir>/src/navigation$1','^utils(.*)$': '<rootDir>/src/utils$1','^components(.*)$': '<rootDir>/src/components$1','^services(.*)$': '<rootDir>/src/services$1',// Another example for using a wildcard character
        '^~(.*)$': '<rootDir>/src$1'
      }
    }
  }
}

参考 - https://resir014.xyz/posts/2019/03/13/using-typescript-absolute-paths-in-cra-20

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。