我意识到这个问题已经被问过多次了,但对我来说却无济于事。
我正在尝试创建create-react-app项目的静态版本,但出现以下错误:
create-react-app
Uncaught SyntaxError: Unexpected token < 1.ca81c833.chunk.js:1 Uncaught SyntaxError: Unexpected token < main.7ced8661.chunk.js:1
由于这些文件已缩小,因此我不确定从哪里开始调试它们。
根据其他SO响应,这是我尝试过的一些事情:
//Original index.html file, which gets included in the built file: <script type="text/babel" src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script> //package.json "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", //.babelrc file { "presets": ["react", "es2015", "stage-1"] }
不知道这是否相关,但是我在我的Express服务器上有这个,我认为这是标准的:
if (process.env.NODE_ENV === "production") { app.use(express.static('client/built')); app.get("*", (req, res) => { res.sendFile(require('path') .resolve(__dirname, 'client', 'build', 'index.html')); }) }
假设这实际上是一个JSX问题,那么整个过程就很混乱-不create-react-app应该自动处理JSX吗?
更新 :我刚刚发布了这个问题,但是已经有了相关的更新。通过运行pm2 serve build,我可以通过pm2为页面提供静态服务,因此我认为问题可能出在我的服务器配置上。
pm2 serve build
我最终在这里找到答案:https : //github.com/facebook/create-react- app/issues/1812
我从上方修剪了完整的解决方案,但我进行了更改:
app.use(express.static('client/build')); app.get("*", (req, res) => { res.sendFile(require('path') .resolve(__dirname, 'client', 'build', 'index.html')); })
至:
const root = require('path').join(__dirname, 'client', 'build') app.use(express.static(root)); app.get("*", (req, res) => { res.sendFile('index.html', { root }); })
我对第一个程序段不起作用肯定感到有些奇怪。我认为这与我的React项目中的相对链接有关,因为index.html尽管出现了错误,但确实将文件传递给了浏览器。也许一个完全静态的文件可以与第一个块一起使用,但是我想知道那是否正确。
index.html