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

Next.js/React应用pm2启动报错:SyntaxError: Unexpected token '<'

解决Next.js+pm2启动时出现SyntaxError: Unexpected token '<'的问题

问题根源

这个错误是因为Node尝试将HTML内容当作JavaScript模块解析,通常由以下原因导致:

  • 未构建Next.js生产环境代码就直接用pm2启动
  • pm2启动命令或工作目录配置错误,导致加载了错误的文件(比如HTML而非JS入口文件)

解决方案

1. 先构建生产环境代码

Next.js开发模式(npm run dev)和生产模式分离,必须先执行构建命令生成生产包:

npm run build

执行完成后,项目根目录会生成.next文件夹,包含编译后的生产代码。

2. 用正确的pm2命令启动生产服务

不要用开发模式的npm run dev启动pm2,生产环境应使用Next.js的start脚本:

pm2 start npm --name "your-app-name" -- start
  • --name:给应用设置管理名称,方便pm2识别
  • -- start:传递给npm的参数,对应package.json里的start脚本(Next.js默认是next start,启动生产服务器)

3. 确保pm2工作目录正确

如果pm2启动时的工作目录不是项目根目录,会找不到.next文件夹或依赖,可通过--cwd指定:

pm2 start npm --name "your-app-name" --cwd /path/to/your/project -- start

4. (可选)使用pm2配置文件管理

创建ecosystem.config.js配置文件,统一管理应用配置:

module.exports = {
  apps: [
    {
      name: 'your-app-name',
      script: 'npm',
      args: 'start',
      cwd: '/path/to/your/project',
      env: {
        NODE_ENV: 'production'
      }
    }
  ]
};

启动命令:

pm2 start ecosystem.config.js

5. 配合Apache反向代理的配置(如果需要)

如果要通过Apache对外提供服务,需配置反向代理指向Next.js的3000端口:

  1. 启用Apache代理模块:
a2enmod proxy proxy_http
systemctl restart apache2
  1. 添加虚拟主机配置(比如/etc/apache2/sites-available/your-app.conf):
<VirtualHost *:80>
    ServerName your-domain.com

    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/
</VirtualHost>
  1. 启用站点并重启Apache:
a2ensite your-app.conf
systemctl restart apache2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:55:37