d3.js next.js + typescript + jest意外的标记'export'

bksxznpy  于 2022-11-12  发布在  TypeScript
关注(0)|答案(1)|浏览(161)

当我尝试在我的Typescript Next.js项目中运行jest时,出现以下错误:

Details:

    node_modules/d3-scale/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

       7 | import { useRouter } from 'next/router';
       8 | import { gql } from '@apollo/client';
    >  9 | import { scaleLinear } from 'd3-scale';

我已经尝试在我的jest配置中将d3-scale添加到transformIgnorePatterns中。

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});
const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/', '<rootDir>/pages/test.tsx'],
  moduleNameMapper: {
    '\\.(scss|sass|css)$': 'identity-obj-proxy',
  },
  transform: {
    '\\.[jt]sx?$': 'babel-jest',
  },
  transformIgnorePatterns: [
    '/node_modules/(?!d3-scale)',
  ],
};
module.exports = createJestConfig(customJestConfig);
piok6c0g

piok6c0g1#

您不能在Next.js中覆盖transformIgnorePatterns,只能扩展它。
有效的解决方法可以是(在您的jest.config.js中):

async function jestConfig() {
  const nextJestConfig = await createJestConfig(customJestConfig)()
  nextJestConfig.transformIgnorePatterns[0] = '/node_modules/(?!d3-scale)/'
  return nextJestConfig
}

module.exports = jestConfig
//module.exports = createJestConfig(customJestConfig)

相关问题