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

Next.js中使用@ionic/react出现Cannot use import statement outside of a module错误

解决Next.js + Ionic React的"Cannot use import statement outside a module"错误

1. 弃用next-transpile-modules,改用官方内置配置

Next.js 12及以上版本已内置包转译能力,第三方的next-transpile-modules与新版SWC编译器兼容性不佳,直接替换为官方配置:

若使用CommonJS(删除package.json里的"type": "module"):

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ["@ionic/react", "@ionic/core", "@stencil/core", "ionicons"],
  swcMinify: true,
};

module.exports = nextConfig;

若使用ES模块(保留package.json的"type": "module"):

将next.config.js重命名为next.config.mjs,内容改为:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ["@ionic/react", "@ionic/core", "@stencil/core", "ionicons"],
  swcMinify: true,
};

export default nextConfig;

2. 修复错误的basePath配置

你当前配置的basePath: "'./src"存在两处问题:

  • 多了不必要的单引号
  • basePath是部署时的URL前缀(比如/my-app),不是源码目录指定项。如果页面在src/pages,Next.js会自动识别,直接删除该配置项即可。

3. 统一模块系统格式

如果package.json设置了"type": "module",所有配置文件需遵循ES模块规范:

  • 配置文件后缀改为.mjs
  • 用import/export替代require/module.exports

若不想折腾模块格式,直接删除package.json中的"type": "module",保持CommonJS格式更省心。

4. 清理缓存并重装依赖

执行以下命令彻底重置依赖和缓存:

rm -rf node_modules package-lock.json
npm install
npm run build -- --clean
npm run dev

5. 验证Ionic初始化位置

确保setupIonicReact()在组件外部调用(你当前代码已符合要求),不要放到组件内部或useEffect中,避免SSR时出现异常。

6. 对齐TS配置

确保tsconfig.json的moduleResolution与模块系统匹配:

{
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "node16", // 对应ES模块;用CommonJS则设为"node"
    // 其他原有配置...
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 22:14:52