繁体   English   中英

将index.html移到公用文件夹时设置新的React项目时出错

[英]Error setting up new React project when moving index.html to public folder

我一直在努力解决一个看似简单的问题。 我当时正在建立一个新的React Project并构建我的文件夹。 我有这样的事情:

/node_modules
/public
   |__ 0.bundle.js
   |__ bundle.js
   // the goal is to move index.html in this folder
/src
   |__components
   App.js
   ClientApp.js
.babelrc
.eslintrc
index.html
package.json
server.js
webpack.config.js
yarn.lock

现在我的索引文件看起来像这样:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>React Test</title>
</head>
<body>
  <div id="app"><%= body %></div>
  <script src="/public/bundle.js"></script>
</body>
</html>

我的server.js是:

require('babel-register')

const express = require('express')
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const ReactRouter = require('react-router-dom')
const StaticRouter = ReactRouter.StaticRouter
const _ = require('lodash')
const fs = require('fs')
const PORT = 5000
const baseTemplate = fs.readFileSync('./index.html')
const template = _.template(baseTemplate)
const App = require('./src/App').default

const server = express()

server.use('/public', express.static('./public'))

server.use((req, res) => {
  const body = ReactDOMServer.renderToString(
    React.createElement(StaticRouter, {location: req.url, context: {}},
      React.createElement(App)
    )
  )

  res.write(template({body: body}))
  res.end()
})

console.log('listening on port', PORT)
server.listen(PORT)

一切工作都像一个超级按钮(服务器和客户端渲染),现在我想做一个简单的更改并将index.html文件移到/public文件夹中。 我做了它更新指向它的各个文件,以及index在哪里寻找bundle.js. 文件。 所以我的新index.html是:

...
<body>
  <div id="app"><%= body %></div>
  <!-- <script src="/public/bundle.js"></script> I actually removed this -->
  <script src="bundle.js"></script>
</body>
...

我的服务器已更新为:

...
const baseTemplate = fs.readFileSync('./public/index.html')
const template = _.template(baseTemplate)
const App = require('./src/App').default

...
server.listen(PORT)

使用此设置,客户端渲染仍然可以工作,但是服务器端渲染会引发错误:

Uncaught SyntaxError: Unexpected token <

我花了一段时间才找出问题所在。 显然在server.js能够检测该文件后,我将它移动到public文件夹(如果我检查HTML其实它是有),但它有麻烦装载实际应用(指JS)。 我觉得进行此更改破坏了我现在理所当然的一些参考。 关于在哪里寻找我的错误有任何想法吗?

有趣的是,我发现了问题所在,我的配置也遇到了涉及webpack问题,我跳过了。 我没有根据新配置更新output路径。

output: {
  path: path.join(__dirname, '/public'),
  filename: 'bundle.js',
  // publicPath: '/public/' --> This was causing the error
  publicPath: '/js/'
},

为什么这是造成错误的原因是由于,如果事实index.html被放置在主文件夹(因为它最初是),那么它需要寻找内侧束public文件夹作为旧webpack与指定的配置publicPath 移动后index.html里面public文件夹,捆现在是在同一个文件夹中index.html文件,所以我们应该参考的路径现在是index自己的文件夹。 这将转换为以上代码段中指定的新publicPath

我希望这可以帮助其他人,我应该更加了解我的webpack配置,并且不会遇到这个问题。 编码愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM