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

React项目引入swiperjs报错:请求的'react'模块应为CommonJS类型求助

错误触发原因

该错误是项目模块规范不兼容导致的:

  • 你使用的高版本Swiper(v8及以上)的React组件基于ES模块规范开发,内部使用import { useEffect, useLayoutEffect } from 'react'的命名导入语法调用React API
  • 你当前项目依赖的React包为CommonJS格式,老版CommonJS规范的React不支持ES模块的命名导入写法,仅支持默认导入后再解构对应API,和错误提示给出的示例逻辑一致
解决方法

你可以根据自己的项目情况任选以下方案:

方案1:降级Swiper版本(最省事,优先推荐)

高版本Swiper对旧项目的CommonJS模块规范兼容性差,直接降级到v7.x稳定版即可解决问题,执行安装命令:

npm install swiper@7

该版本的Swiper React适配层完全基于CommonJS规范编写,和你现有项目的模块规则匹配,不会触发导入错误。

方案2:配置构建工具转译Swiper(适配高版本Swiper)

从报错信息里的page: '/'字段判断你大概率使用的是Next.js框架,可以在next.config.js中添加transpilePackages配置,将Swiper及其依赖包加入构建转译列表,让构建工具统一处理模块规范:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['swiper', 'ssr-window', 'dom7'],
}

module.exports = nextConfig

如果是其他构建工具(如Webpack、Vite),可搜索对应工具的ES模块转译CommonJS规则进行配置。

额外注意事项

你当前的代码仅导入了Swiper和SwiperSlide组件,还未实际使用,后续需要将轮播内容包裹到对应组件内轮播才能生效,示例写法:

import React from "react";
import { Swiper, SwiperSlide } from 'swiper/react';
// 还需要引入Swiper的样式文件,v7版本引入路径如下
import 'swiper/css';

function HomeBanner(props) {
    return (
        <Swiper>
            <SwiperSlide>
                <img src="img/slider/home-3/home-banner/1.jpg" alt="" />
                <div className="">
                    <h5>Mega Sale Nov 2019</h5>
                    <h3>
                        Double Combo With <br />
                        The Body Shop
                    </h3>
                    <p>Sale up to <strong>50% Off </strong></p>
                    <a className="ps-btn" href="#">Shop Now</a>
                </div>
            </SwiperSlide>
            <SwiperSlide>
                <img src="img/slider/home-3/home-banner/2.jpg" alt="" />
                <div className="">
                    <h5>Mega Sale Nov 2017</h5>
                    <h3>
                        IKEA Minimalist <br />
                        Otoman
                    </h3>
                    <p>Discount <strong>50% Off </strong></p>
                    <a className="ps-btn" href="#">Shop Now</a>
                </div>
            </SwiperSlide>
        </Swiper>
    )
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:15:01