简体   繁体   English

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

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

jest fails to import the import of my import which is causing npm run test command to fail with SyntaxError: Unexpected token 'export' at first line of my bar.ts file. jest无法导入我的导入,这导致npm run test命令失败,并在我的bar.ts文件的第一行出现SyntaxError: Unexpected token 'export' For this example foo.js is a local file, not a node module.对于这个例子foo.js是一个本地文件,而不是一个节点模块。 I can change foo.js to foo.ts and change the import in bar.ts but that is not the solution.我可以将foo.js更改为foo.ts并更改bar.ts中的导入,但这不是解决方案。

Files in my src folder:我的src文件夹中的文件:

  • foo.js : foo.js
export const magicNumber = 42; 
  • bar.ts : bar.ts
import { magicNumber } from './foo.js';

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

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

Files in the root folder:文件夹中的文件:

  • jest.config.js : jest.config.js
export default {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
  • package.json : package.json
{
  "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"
}
  • tsconfig.json : tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",                         
    "module": "ESNext",                    
    "outDir": "./dist",                                       
    "strict": true,                          
    "esModuleInterop": true,                  
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true,
    "declaration": true,
    "moduleResolution": "node"
  },
  "include": ["./src/**/*.ts"]
}

So the problem is that both ts-jest and jest are tricky to set up for the ES6 import/export syntax.所以问题是ts-jestjest都很难为 ES6 导入/导出语法设置。 I did exactly that by:我正是这样做的:

  1. Installing both jest and ts-jest >= 27.0.0 versions.安装jestts-jest >= 27.0.0 版本。
  2. Using this minimal config:使用这个最小配置:

tsconfig.json : tsconfig.json

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

jest.config.ts : jest.config.ts

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

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

    // from https://stackoverflow.com/a/57916712/15076557
    transformIgnorePatterns: [
        'node_modules/(?!(module-that-needs-to-be-transformed)/)' 
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM