首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Nextjs & Jest转换/转换不使用esm模块

Nextjs & Jest转换/转换不使用esm模块
EN

Stack Overflow用户
提问于 2022-03-10 16:12:22
回答 1查看 1.2K关注 0票数 4

我对此做了大量的研究,并找到了相当多的解决方案。我已经找到了一种类似于解决方案的方法,并希望transformtransformIgnorePatterns能够正常工作。不过,似乎我唯一能做到的就是在我的__mocks__文件夹中手动添加一些模拟模块。

不确定这是否是由于在Nextjs中使用Jest而造成的?

这是我的jest.config.js

代码语言:javascript
复制
const nextJest = require("next/jest");

const esModules = ["react-markdown", "rehype-raw", "remark-gfm"].join("|");

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
});

// Add any custom config to be passed to Jest
const customJestConfig = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    // Handle module aliases (this will be automatically configured for you soon)
    "^@/components/(.*)$": "<rootDir>/components/$1",

    "^@/pages/(.*)$": "<rootDir>/pages/$1",
  },
  testEnvironment: "jest-environment-jsdom",
  transform: {
    [`(${esModules}).+\\.js$`]: "babel-jest",
  },
  transformIgnorePatterns: [
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`,
  ],
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);

我已经读到我也需要一个babel.config.js。这是那个文件:

代码语言:javascript
复制
module.exports = {
  presets: ["next/babel", "@babel/preset-env"],
};
EN

回答 1

Stack Overflow用户

发布于 2022-07-10 07:12:11

这里有一个解决方案,以防有人遇到同样的问题,但正在使用NextJs 12.2next/jestJest 28

Jest为ECMAScript模块提供了一些实验支持但是模块“还没有转移到next/jest

因此,我们需要使用transformIgnorePatterns来防止ESM文件被转换。

更改transformIgnorePatterns的默认配置是next/jest,请参阅下面的解决方案。

代码语言:javascript
复制
// jest.config.js
const nextJest = require('next/jest')

const createJestConfig = nextJest({
  // Path to Next.js app to load next.config.js
  dir: './'
})

/** @type {import('@jest/types').Config.InitialOptions} */
const customJestConfig = {
  /**
   * Custom config goes here, I am not adding it to keep this example simple.
   * See next/jest examples for more information.
   */
 }

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
  transformIgnorePatterns: [
    // The regex below is just a guess, you might tweak it
    'node_modules/(?!(react-markdown|rehype-raw|remark-gfm)/)',
  ]
})

我创建了一个存储库,用于完全引用正在使用swiper/react的一个案例所需的设置。https://github.com/markcnunes/with-jest-and-esm

请记住,对于未来的Next.js / next/js版本,此设置可能需要更改,但只是共享此方法,以防此方法对使用此设置的其他人有用。

我还对另一个问题使用了这个答案,以防您正在寻找与swiper/react相关的解决方案。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71427330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档