沙哑的可以解决tsconfig.ts的路径

发布于 2025-02-12 15:43:34 字数 8287 浏览 0 评论 0原文

我正在使用开玩笑来进行单元测试,并且在我的tsconfig.json中有自定义路径,它在本地罚款。

但是,当我尝试通过赫斯基和绒毛阶段进行更改时,它会犯“找不到测试文件”或“无法解决 @core/..”

我们必须将Husky的自定义配置用于允许亲戚穿越沙哑的道路?

我的tsconfig.json:

{
  "ts-node": {
    "transpileOnly": true,
    "require": [ "typescript-transform-paths/register" ]
  },
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDirs": ["./src", "./build"],
    "baseUrl": "src",
    "paths": {
      "@core/*": ["core/*"],
      "@api/*": ["api/*"]
    },
    "plugins": [
      { "transform": "typescript-transform-paths" },
      { "transform": "typescript-transform-paths", "afterDeclarations": true }
    ],
    "resolveJsonModule": true,
    "declaration": true,
    "outDir": "./build",
    "importHelpers": true,
    "importsNotUsedAsValues": "remove",
    "noEmitOnError": true,
    "declarationDir": "build/@types",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "useUnknownInCatchVariables": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "allowUnusedLabels": true,
    "allowUnreachableCode": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "tests/**/*.ts", ".husky/**/*"],
  "exclude": ["node_modules", ".vscode"]
}

我的jest.config.ts文件:

// For a detailed explanation regarding each configuration property and type check, visit:
// https://jestjs.io/docs/configuration

// eslint-disable-next-line import/no-extraneous-dependencies
import { pathsToModuleNameMapper } from "ts-jest/dist";
import { compilerOptions } from "./tsconfig.json";

export default {
    // All imported modules in your tests should be mocked automatically
    automock: false,

    // Stop running tests after `n` failures
    // bail: 0,

    // The directory where Jest should store its cached dependency information
    // cacheDirectory: "C:\\Users\\ssoylu\\AppData\\Local\\Temp\\jest",

    // Automatically clear mock calls, instances, contexts and results before every test
    clearMocks: true,

    // Indicates whether the coverage information should be collected while executing the test
    collectCoverage: false,

    // An array of glob patterns indicating a set of files for which coverage information should be collected
    collectCoverageFrom: ["<rootDir>/**/*.ts"],

    // The directory where Jest should output its coverage files
    coverageDirectory: "tests/coverage",

    // An array of regexp pattern strings used to skip coverage collection
    coveragePathIgnorePatterns: ["/tests/"],

    // Indicates which provider should be used to instrument code for coverage
    coverageProvider: "babel",

    // A list of reporter names that Jest uses when writing coverage reports
    coverageReporters: ["json", "text", "lcov", "clover"],

    // An object that configures minimum threshold enforcement for coverage results
    // coverageThreshold: undefined,

    // A path to a custom dependency extractor
    // dependencyExtractor: undefined,

    // Make calling deprecated APIs throw helpful error messages
    errorOnDeprecated: true,

    // The default configuration for fake timers
    // fakeTimers: {
    //   "enableGlobally": false
    // },

    // Force coverage collection from ignored files using an array of glob patterns
    // forceCoverageMatch: [],

    // A path to a module which exports an async function that is triggered once before all test suites
    // globalSetup: undefined,

    // A path to a module which exports an async function that is triggered once after all test suites
    // globalTeardown: undefined,

    // A set of global variables that need to be available in all test environments
    // globals: {},

    // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
    maxWorkers: "10%",

    // An array of directory names to be searched recursively up from the requiring module's location
    moduleDirectories: ["src", "node_modules"],

    // An array of file extensions your modules use
    moduleFileExtensions: ["js", "mjs", "ts", "tsx", "json"],

    // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),

    // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
    // modulePathIgnorePatterns: [],

    // Activates notifications for test results
    // notify: false,

    // An enum that specifies notification mode. Requires { notify: true }
    // notifyMode: "failure-change",

    // A preset that is used as a base for Jest's configuration
    preset: "ts-jest",

    // Run tests from one or more projects
    // projects: undefined,

    // Use this configuration option to add custom reporters to Jest
    // reporters: undefined,

    // Automatically reset mock state before every test
    resetMocks: true,

    // Reset the module registry before running each individual test
    // resetModules: false,

    // A path to a custom resolver
    // resolver: undefined,

    // Automatically restore mock state and implementation before every test
    // restoreMocks: false,

    // The root directory that Jest should scan for tests and modules within
    rootDir: "./tests",

    // A list of paths to directories that Jest should use to search for files in
    // roots: ["tests", "src"],

    // Allows you to use a custom runner instead of Jest's default test runner
    // runner: "jest-runner",

    // The paths to modules that run some code to configure or set up the testing environment before each test
    // setupFiles: [],

    // A list of paths to modules that run some code to configure or set up the testing framework before each test
    // setupFilesAfterEnv: [],

    // The number of seconds after which a test is considered as slow and reported as such in the results.
    slowTestThreshold: 5,

    // A list of paths to snapshot serializer modules Jest should use for snapshot testing
    // snapshotSerializers: [],

    // The test environment that will be used for testing
    // testEnvironment: "jest-environment-node",

    // Options that will be passed to the testEnvironment
    // testEnvironmentOptions: {},

    // Adds a location field to test results
    // testLocationInResults: false,

    // The glob patterns Jest uses to detect test files
    testMatch: ["**/launcher.test.ts?(x)"],

    // This option allows the use of a custom results processor
    // testResultsProcessor: undefined,

    // This option allows use of a custom test runner
    // testRunner: "jest-circus/runner",

    // A map from regular expressions to paths to transformers
    // transform: undefined,

    // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
    // transformIgnorePatterns: [
    //   "\\\\node_modules\\\\",
    //   "\\.pnp\\.[^\\\\]+$"
    // ],

    // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
    // unmockedModulePathPatterns: undefined,

    // Indicates whether each individual test should be reported during the run
    // verbose: undefined,

    // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
    // watchPathIgnorePatterns: [],

    // Whether to use watchman for file crawling
    // watchman: true,
};

I'm using Jest to make my unit tests and I have custom paths in my tsconfig.json which works all fines in local.

But when I try to commit my changes through husky and lint-staged, it makes errors like "can't find test files" or "can't resolve @core/.."

Do we have to make a custom config of husky to allows relatives paths through husky ?

my tsconfig.json :

{
  "ts-node": {
    "transpileOnly": true,
    "require": [ "typescript-transform-paths/register" ]
  },
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "rootDirs": ["./src", "./build"],
    "baseUrl": "src",
    "paths": {
      "@core/*": ["core/*"],
      "@api/*": ["api/*"]
    },
    "plugins": [
      { "transform": "typescript-transform-paths" },
      { "transform": "typescript-transform-paths", "afterDeclarations": true }
    ],
    "resolveJsonModule": true,
    "declaration": true,
    "outDir": "./build",
    "importHelpers": true,
    "importsNotUsedAsValues": "remove",
    "noEmitOnError": true,
    "declarationDir": "build/@types",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "useUnknownInCatchVariables": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "allowUnusedLabels": true,
    "allowUnreachableCode": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*.ts", "tests/**/*.ts", ".husky/**/*"],
  "exclude": ["node_modules", ".vscode"]
}

my jest.config.ts file :

// For a detailed explanation regarding each configuration property and type check, visit:
// https://jestjs.io/docs/configuration

// eslint-disable-next-line import/no-extraneous-dependencies
import { pathsToModuleNameMapper } from "ts-jest/dist";
import { compilerOptions } from "./tsconfig.json";

export default {
    // All imported modules in your tests should be mocked automatically
    automock: false,

    // Stop running tests after `n` failures
    // bail: 0,

    // The directory where Jest should store its cached dependency information
    // cacheDirectory: "C:\\Users\\ssoylu\\AppData\\Local\\Temp\\jest",

    // Automatically clear mock calls, instances, contexts and results before every test
    clearMocks: true,

    // Indicates whether the coverage information should be collected while executing the test
    collectCoverage: false,

    // An array of glob patterns indicating a set of files for which coverage information should be collected
    collectCoverageFrom: ["<rootDir>/**/*.ts"],

    // The directory where Jest should output its coverage files
    coverageDirectory: "tests/coverage",

    // An array of regexp pattern strings used to skip coverage collection
    coveragePathIgnorePatterns: ["/tests/"],

    // Indicates which provider should be used to instrument code for coverage
    coverageProvider: "babel",

    // A list of reporter names that Jest uses when writing coverage reports
    coverageReporters: ["json", "text", "lcov", "clover"],

    // An object that configures minimum threshold enforcement for coverage results
    // coverageThreshold: undefined,

    // A path to a custom dependency extractor
    // dependencyExtractor: undefined,

    // Make calling deprecated APIs throw helpful error messages
    errorOnDeprecated: true,

    // The default configuration for fake timers
    // fakeTimers: {
    //   "enableGlobally": false
    // },

    // Force coverage collection from ignored files using an array of glob patterns
    // forceCoverageMatch: [],

    // A path to a module which exports an async function that is triggered once before all test suites
    // globalSetup: undefined,

    // A path to a module which exports an async function that is triggered once after all test suites
    // globalTeardown: undefined,

    // A set of global variables that need to be available in all test environments
    // globals: {},

    // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
    maxWorkers: "10%",

    // An array of directory names to be searched recursively up from the requiring module's location
    moduleDirectories: ["src", "node_modules"],

    // An array of file extensions your modules use
    moduleFileExtensions: ["js", "mjs", "ts", "tsx", "json"],

    // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),

    // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
    // modulePathIgnorePatterns: [],

    // Activates notifications for test results
    // notify: false,

    // An enum that specifies notification mode. Requires { notify: true }
    // notifyMode: "failure-change",

    // A preset that is used as a base for Jest's configuration
    preset: "ts-jest",

    // Run tests from one or more projects
    // projects: undefined,

    // Use this configuration option to add custom reporters to Jest
    // reporters: undefined,

    // Automatically reset mock state before every test
    resetMocks: true,

    // Reset the module registry before running each individual test
    // resetModules: false,

    // A path to a custom resolver
    // resolver: undefined,

    // Automatically restore mock state and implementation before every test
    // restoreMocks: false,

    // The root directory that Jest should scan for tests and modules within
    rootDir: "./tests",

    // A list of paths to directories that Jest should use to search for files in
    // roots: ["tests", "src"],

    // Allows you to use a custom runner instead of Jest's default test runner
    // runner: "jest-runner",

    // The paths to modules that run some code to configure or set up the testing environment before each test
    // setupFiles: [],

    // A list of paths to modules that run some code to configure or set up the testing framework before each test
    // setupFilesAfterEnv: [],

    // The number of seconds after which a test is considered as slow and reported as such in the results.
    slowTestThreshold: 5,

    // A list of paths to snapshot serializer modules Jest should use for snapshot testing
    // snapshotSerializers: [],

    // The test environment that will be used for testing
    // testEnvironment: "jest-environment-node",

    // Options that will be passed to the testEnvironment
    // testEnvironmentOptions: {},

    // Adds a location field to test results
    // testLocationInResults: false,

    // The glob patterns Jest uses to detect test files
    testMatch: ["**/launcher.test.ts?(x)"],

    // This option allows the use of a custom results processor
    // testResultsProcessor: undefined,

    // This option allows use of a custom test runner
    // testRunner: "jest-circus/runner",

    // A map from regular expressions to paths to transformers
    // transform: undefined,

    // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
    // transformIgnorePatterns: [
    //   "\\\\node_modules\\\\",
    //   "\\.pnp\\.[^\\\\]+
quot;
    // ],

    // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
    // unmockedModulePathPatterns: undefined,

    // Indicates whether each individual test should be reported during the run
    // verbose: undefined,

    // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
    // watchPathIgnorePatterns: [],

    // Whether to use watchman for file crawling
    // watchman: true,
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瞄了个咪的 2025-02-19 15:43:34

您应该在jest.config.ts中配置路径,以便开玩笑解决模块。

module.exports = {
  // ... existing JEST config
  "moduleNameMapper": {
    "@core/(.*)": [
      "<rootDir>/src/core/$1"
    ],
    "@api/(.*)": [
      "<rootDir>/src/api/$1"
    ]
  }
}

You should configure your paths in jest.config.ts in order for Jest to resolve the module.

module.exports = {
  // ... existing JEST config
  "moduleNameMapper": {
    "@core/(.*)": [
      "<rootDir>/src/core/$1"
    ],
    "@api/(.*)": [
      "<rootDir>/src/api/$1"
    ]
  }
}
牵你手 2025-02-19 15:43:34

沙哑!

假设#1 您没有绒毛阶段 config?

HuskY!

Assumption #1 You have no lint-staged config? ????

Update: after thinking again, if this is an issue, then you have another issue, as this would only solve the problem for linting but you're saying it's the same for Jest. Anyway, there could be 2 problems ^^ disguised as 1.`

It's either lintstagedrc.yml|yaml|json

...or example from package.json

"lint-staged": {
    "*.{ts,tsx,json,scss,md}": [
      "prettier --write"
    ],
    "*.{ts,tsx}": [
      "eslint --max-warnings=0"
    ]
  },

It's also explained by lint-staged:

Assumption #2 different path alias notation

It's probably nothing, but you could also just set the paths like this:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@api": ["./api"],
      "@core": ["./core"],
    }
  }
}

I haven't tested it with:

  • * notation as in your config
  • @ prefix is also not used in our project
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文