首页 > 解决方案 > Create React App 生产构建成功,但生成的代码有错误

问题描述

我有一个我一直在使用 webpack-dev-server 开发的 create-react-app React 应用程序,并且一切都在开发中工作。

但是,当我为生产构建时,输出构建不起作用并且有以下控制台错误:

Uncaught SyntaxError: Unexpected token < :4001/static/js/1.33f1f515.chunk.js/:1
Uncaught SyntaxError: Unexpected token < :4001/static/js/main.625fef55.chunk.js/:1
Uncaught SyntaxError: Unexpected token < manifest.json:1 Manifest: Line: 1, column: 1, Unexpected token.

标签: reactjswebpackcreate-react-appwebpack-4

解决方案


您在生产环境中使用 express (nodejs) 服务器吗?

如果是,则检查静态文件服务配置。问题是/manifest.json/static/js/main.625fef55.chunk.js/等正在返回 index.html 而不是清单或 js 文件。

这是我的示例服务器文件-

const express = require('express');
const path = require('path');
const app = express();

app.use('/', express.static(path.join(__dirname, '../build')));

app.use(function(req, res, next) {
  //console.log(req.originalUrl);
  next();
});

// to check if server is running
app.get('/ping', (req, res) => {
  res.json({
    success: true,
    message: 'pong'
  })
});

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, '../build', 'index.html'));
});

module.exports = app;

推荐阅读