如何使 ts-jest 使用我导入中导入的 js 文件的 import/export 语法?

How to make ts-jest work with import/export syntax of the js files that are being imported in my imports?

jest 无法导入我的导入,这导致 npm run test 命令失败,在我的 bar.ts 文件的第一行显示 SyntaxError: Unexpected token 'export'。对于这个例子 foo.js 是一个本地文件,而不是一个节点模块。我可以将 foo.js 更改为 foo.ts 并更改 bar.ts 中的导入,但这不是解决方案。

我的 src 文件夹中的文件:

export const magicNumber = 42; 
import { magicNumber } from './foo.js';

export const secondMagicNumber = magicNumber / 2; 
import { secondMagicNumber } from './bar';
import assert from 'assert';

it('should work', function() {
    assert.strictEqual(secondMagicNumber, 21);
});

root 文件夹中的文件:

export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
{
  "name": "testing-with-jest",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/jest": "^26.0.20",
    "jest": "^26.6.3",
    "ts-jest": "^26.5.2",
    "typescript": "^4.2.2"
  },
  "type": "module"
}
{
  "compilerOptions": {
    "target": "ESNext",                         
    "module": "ESNext",                    
    "outDir": "./dist",                                       
    "strict": true,                          
    "esModuleInterop": true,                  
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "moduleResolution": "node"
  },
  "include": ["./src/**/*.ts"]
}

所以问题是 ts-jestjest 都很难设置为 ES6 import/export 语法。我正是这样做的:

  1. 正在安装 jestts-jest >= 27.0.0 版本。
  2. 使用这个最小配置:

tsconfig.json:

{
  "compilerOptions": {                    
    "esModuleInterop": true, 
    "allowJs": true                
  }
}

jest.config.ts:

export default {
    globals: {
        extensionsToTreatAsEsm: ['.ts', '.js'],
        'ts-jest': {
            useESM: true
        }
    },

    preset: 'ts-jest/presets/js-with-ts-esm',

    // from 
    transformIgnorePatterns: [
        'node_modules/(?!(module-that-needs-to-be-transformed)/)' 
    ]
}