You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中使用Swiper测试时出现import语句语法错误求助

Next.js + Swiper 测试报错:SyntaxError: Cannot use import statement outside a module

问题详情

在Next.js项目中使用Swiper组件并执行Jest测试时,出现以下错误:

import { Swiper } from './swiper.js';
SyntaxError: Cannot use import statement outside a module

使用的依赖版本:

  • next: ^12.3.0
  • swiper: ^8.4.5
  • jest: ^29.0.2

jest.config.js 配置

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

const createJestConfig = nextJest({
  dir: './'
});

const customJestConfig = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
    '^@/public/(.*)$': '<rootDir>/public/$1'
  },

  setupFilesAfterEnv: ['./jest.setup.js', './src/__mocks__/mocks.ts'],
  clearMocks: true,
  collectCoverage: true,
  collectCoverageFrom: [
    './src/**/*.{js,jsx,ts,tsx}',
    '!./src/**/_*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**'
  ],

  coverageThreshold: {
    // global: {
    //   branches: 80,
    //   functions: 80,
    //   lines: 80,
    //   statements: 80,
    // },
  },
  testEnvironment: 'jest-environment-jsdom'
};

module.exports = createJestConfig(customJestConfig);

组件实现代码

import { Box, Typography } from '@mui/material';
import React, { useState } from 'react';
import SwiperCore, { Navigation, Pagination, Virtual } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/react';

SwiperCore?.use([Virtual, Navigation, Pagination]);

export const GallerySlider = () => {
  const [slides] = useState(
    Array.from({ length: 500 }).map((_, index) => `Slide ${index + 1}`)
  );

  return (
    <Box width={'100%'} height={'50vh'}>
      <Typography
        variant={'h2'}
        textAlign={'center'}
        marginBottom={{ xs: '2rem', md: '4rem' }}
      >
        Galeria
      </Typography>
      <Swiper
        slidesPerView={3}
        centeredSlides={true}
        spaceBetween={30}
        pagination={{ type: 'fraction' }}
        navigation={true}
        virtual
      >
        {slides.map((slideContent, index) => (
          <SwiperSlide key={slideContent} virtualIndex={index}>
            {slideContent}
          </SwiperSlide>
        ))}
      </Swiper>
    </Box>
  );
};

解决方案

错误原因是Swiper 8+采用ES模块语法,而Jest默认不会转译node_modules中的ES模块文件,导致测试环境无法识别import语句。需要修改Jest配置,让它转译Swiper及其依赖的包:

  1. 在jest.config.js的customJestConfig中添加transformIgnorePatterns配置:
const customJestConfig = {
  // ... 其他已有配置
  transformIgnorePatterns: [
    '/node_modules/(?!swiper|ssr-window|dom7)',
  ],
  // ... 其他已有配置
};
  1. 保存配置后重新运行测试即可。

说明:ssr-window和dom7是Swiper的依赖包,同样使用ES模块,所以需要一起加入转译白名单。

内容的提问来源于stack exchange,提问作者Diego Wagner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:30:53