Skip to content

✨ Add debug output for SWC and automatic Jest module mapping #962

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
874 changes: 0 additions & 874 deletions .yarn/releases/yarn-3.6.4.cjs

This file was deleted.

875 changes: 875 additions & 0 deletions .yarn/releases/yarn-3.8.6.cjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ plugins:
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
spec: '@yarnpkg/plugin-workspace-tools'

yarnPath: .yarn/releases/yarn-3.6.4.cjs
yarnPath: .yarn/releases/yarn-3.8.6.cjs
40 changes: 20 additions & 20 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,33 @@
"@commitlint/cli": "^17.8.1",
"@commitlint/config-conventional": "^17.8.1",
"@commitlint/prompt": "^17.8.1",
"@swc-node/jest": "^1.5.6",
"@swc/core": "^1.3.102",
"@swc/helpers": "^0.5.3",
"@swc-node/jest": "^1.8.12",
"@swc/core": "^1.10.18",
"@types/jest": "^29.5.4",
"@types/lodash.has": "^4.5.8",
"@types/lodash.has": "^4.5.9",
"@types/mkdirp": "^1.0.2",
"@types/node": "^18.18.6",
"@types/node": "^18.19.61",
"@types/rimraf": "^3.0.2",
"@types/which": "^2.0.2",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"commitizen": "^4.3.0",
"commitizen": "^4.3.1",
"concurrently": "^7.6.0",
"cosmiconfig": "^8.3.6",
"cross-env": "^7.0.3",
"cross-spawn": "^7.0.3",
"debug": "^4.4.0",
"doctoc": "^2.2.1",
"eslint": "^8.52.0",
"eslint": "^8.57.1",
"eslint-config-airbnb": "19.0.4",
"eslint-config-airbnb-typescript": "^17.1.0",
"eslint-config-prettier": "^8.10.0",
"eslint-plugin-import": "^2.29.0",
"eslint-plugin-jest": "^27.4.3",
"eslint-plugin-jsx-a11y": "^6.7.1",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jest": "^27.9.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^4.6.2",
"glob": "^8.1.0",
"is-ci": "^3.0.1",
"jest": "^29.5.0",
Expand All @@ -90,8 +90,8 @@
"prettier": "^2.8.8",
"read-pkg-up": "^7.0.1",
"rimraf": "^4.1.1",
"swc_mut_cjs_exports": "^0.86.17",
"tslib": "^2.6.2",
"swc_mut_cjs_exports": "^8.0.1",
"tslib": "^2.8.0",
"typescript": "^4.9.5",
"which": "^3.0.0",
"yargs-parser": "^21.1.1"
Expand Down Expand Up @@ -129,12 +129,12 @@
},
"homepage": "https://github.com/hoverinc/hover-javascript#readme",
"devDependencies": {
"@babel/cli": "^7.23.0",
"@babel/core": "^7.23.2",
"@babel/preset-env": "^7.23.2",
"@babel/cli": "^7.25.9",
"@babel/core": "^7.26.0",
"@babel/preset-env": "^7.26.0",
"@babel/preset-typescript": "^7.23.3",
"@types/cross-spawn": "^6.0.4",
"@types/lodash.merge": "^4",
"@types/cross-spawn": "^6.0.6",
"@types/debug": "^4",
"depcheck": "^1.4.7",
"eslint-config-kentcdodds": "^20.5.0",
"husky": "^8.0.3",
Expand All @@ -150,5 +150,5 @@
"optional": true
}
},
"packageManager": "yarn@3.6.4"
"packageManager": "yarn@3.8.6"
}
1 change: 0 additions & 1 deletion src/api/test.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {pathsToModuleNameMapper} from '../paths-to-module-name-mapper'
const pathsToModuleNameMapper = require('../paths-to-module-name-mapper')

const tsconfigMap = {
log: ['src/utils/log'],
Expand Down
3 changes: 3 additions & 0 deletions src/api/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
pathsToModuleNameMapper: require('./paths-to-module-name-mapper'),
}
1 change: 0 additions & 1 deletion src/api/test/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,38 @@
* @see {@link https://github.com/kulshekhar/ts-jest/blob/dd3523cb7571714f06f1ea2ed1e3cf11970fbfce/src/config/paths-to-module-name-mapper.ts}
*/

import type {Config} from '@jest/types'
import type {CompilerOptions} from 'typescript'

type TsPathMapping = Exclude<CompilerOptions['paths'], undefined>
type JestPathMapping = Config.InitialOptions['moduleNameMapper']
/**
* We don't need to escape all chars, so commented out is the real one
* const escapeRegex = (str: string) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
*
* @param {string} str
* @returns {string}
*/
const escapeRegex = str => str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')

// we don't need to escape all chars, so commented out is the real one
// const escapeRegex = (str: string) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
const escapeRegex = (str: string) => str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')
/**
* @typedef {Exclude<import('typescript').CompilerOptions['paths'], undefined>} TsPathMapping
* @typedef {import('@jest/types').Config.InitialOptions['moduleNameMapper']} JestPathMapping
*/

export const pathsToModuleNameMapper = (
mapping: TsPathMapping,
{prefix = '', useESM = false}: {prefix?: string; useESM?: boolean} = {},
): JestPathMapping => {
const jestMap: JestPathMapping = {}
/**
* Converts TypeScript path mappings to Jest module name mappings
*
* @param {TsPathMapping} mapping - The TypeScript path mapping object
* @param {{prefix?: string, useESM?: boolean}} options - Configuration options
* @returns {JestPathMapping}
*/
const pathsToModuleNameMapper = (
mapping,
{prefix = '', useESM = false} = {},
) => {
/** @type {JestPathMapping} */
const jestMap = {}
for (const fromPath of Object.keys(mapping)) {
const toPaths = mapping[fromPath]
// check that we have only one target path
if (toPaths.length === 0) {
console.warn(`Not mapping "${fromPath}" because it has no target.`)

continue
}

Expand All @@ -35,7 +46,6 @@ export const pathsToModuleNameMapper = (
const paths = toPaths.map(target => {
const enrichedPrefix =
prefix !== '' && !prefix.endsWith('/') ? `${prefix}/` : prefix

return `${enrichedPrefix}${target}`
})
const cjsPattern = `^${escapeRegex(fromPath)}$`
Expand All @@ -48,7 +58,6 @@ export const pathsToModuleNameMapper = (
: target
const enrichedPrefix =
prefix !== '' && !prefix.endsWith('/') ? `${prefix}/` : prefix

return `${enrichedPrefix}${enrichedTarget.replace(/\*/g, '$1')}`
})
if (useESM) {
Expand All @@ -74,3 +83,5 @@ export const pathsToModuleNameMapper = (

return jestMap
}

module.exports = pathsToModuleNameMapper
147 changes: 98 additions & 49 deletions src/config/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ const {
readDefaultTsConfig,
tsCompilerOptionsToSwcConfig,
} = require('@swc-node/register/read-default-tsconfig')
const {ifAnyDep, hasFile, fromRoot, hasDevDep} = require('../utils')

const {ifAnyDep, hasFile, fromRoot, hasDevDep, getDebug} = require('../utils')
const {pathsToModuleNameMapper} = require('../api/test')

const {
testMatch,
testMatchGlob,
testMatchExtensions,
} = require('./helpers/test-match')

const debug = getDebug('jest')

const ignores = [
'/node_modules/',
'/__fixtures__/',
Expand All @@ -24,12 +28,48 @@ const ignores = [
'__mocks__',
]

/**
* @type {SwcNodeOptions}
*/
const DEFAULT_SWC_OPTIONS = {
esModuleInterop: true,
module: 'commonjs',
react: {runtime: 'automatic'},
swc: {
jsc: {
target: 'es2020',
experimental: {
plugins: [[require.resolve('swc_mut_cjs_exports'), {}]],
},
parser: {
syntax: 'typescript',
tsx: true,
decorators: false,
dynamicimport: true,
},
loose: true,
externalHelpers: false,
transform: {
react: {
runtime: 'automatic',
},
},
},
},
}

const tsConfig = readDefaultTsConfig()
const swcConfig = merge(
tsCompilerOptionsToSwcConfig(tsConfig, ''),
DEFAULT_SWC_OPTIONS,
)

debug.prefix('tsconfig:paths')(tsConfig.paths)

/**
* Get the path at which `@hover/javascript/jest` is installed in a dependent
* project in order to resolve the Jest preset as sometimes package managers
* nest the preset installation within the `@hover/javascript` installation.
*
* @returns
*/
const getResolvePaths = () => {
try {
Expand All @@ -41,6 +81,54 @@ const getResolvePaths = () => {
}
}

/**
* The default transform is now SWC, however, `ts-jest` will
* still be used if it is installed in the host project
*
* @returns {JestConfig['transform']}
*/
const getTransform = () => {
const log = debug.prefix('transform')

if (hasDevDep('ts-jest')) {
log('Detected `ts-jest` package, using ts-jest transform')

const transform = Object.fromEntries(
// Ensure we can resolve the preset even when
// it's in a nested `node_modules` installation
Object.entries(require('ts-jest/presets').jsWithTs.transform).map(
([glob, [transformer, options]]) => [
glob,
[
require.resolve(transformer),
{
...options,
diagnostics: false,
},
],
],
),
)

log(transform)

return transform
}

log('No `ts-jest` package detected, using default SWC transform')

const transform = {
'^.+\\.(t|j|mj)sx?$': [
require.resolve('@swc-node/jest', getResolvePaths()),
swcConfig,
],
}

log(transform)

return transform
}

/** @type JestConfig */
const jestConfig = {
roots: [fromRoot('.')],
Expand All @@ -55,52 +143,13 @@ const jestConfig = {
testMatch,
testPathIgnorePatterns: [...ignores, '<rootDir>/dist'],
testLocationInResults: true,
// The default transform is now SWC, however, `ts-jest` will
// still be used if it is installed in the host project
transform: hasDevDep('ts-jest')
? Object.fromEntries(
// Ensure we can resolve the preset even when
// it's in a nested `node_modules` installation
Object.entries(require('ts-jest/presets').jsWithTs.transform).map(
([glob, [transformer, options]]) => [
glob,
[
require.resolve(transformer),
{
...options,
diagnostics: false,
},
],
],
),
)
: {
'^.+\\.(t|j)sx?$': [
require.resolve('@swc-node/jest', getResolvePaths()),
/** @type {SwcNodeOptions} */ (
merge(tsCompilerOptionsToSwcConfig(readDefaultTsConfig(), ''), {
esModuleInterop: true,
module: 'commonjs',
swc: {
jsc: {
target: 'es2020',
experimental: {
plugins: [[require.resolve('swc_mut_cjs_exports'), {}]],
},
parser: {
syntax: 'typescript',
tsx: true,
decorators: false,
dynamicimport: true,
},
loose: true,
externalHelpers: false,
},
},
})
),
],
},
moduleNameMapper: debug.trace(
pathsToModuleNameMapper(
debug.trace(swcConfig.paths, 'moduleNameMapper:paths'),
),
'moduleNameMapper',
),
transform: getTransform(),
coveragePathIgnorePatterns: [
...ignores,
'src/(umd|cjs|esm)-entry.js$',
Expand Down
Loading
Loading