4

我正在尝试使用简单的快速服务器运行 SSR React (16.3.0) 应用程序。构建并运行后babel-node server.js出现有关导入的 PNG 文件的错误:

/home/dev/test/src/assets/bg.png:1 (函数 (exports, require, module, __filename, __dirname) { �PNG ^

SyntaxError: Invalid or unexpected token
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Module._extensions..js (module.js:664:10)
    at Object.newLoader [as .js] (/home/dev/test/node_modules/pirates/lib/index.js:88:7)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)

这是我的 server.js:

import express from 'express'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import path from 'path'

import App from './src/components/App'

const app = express()
const port = 4000

const HTMLShell = (html) => `
  <!DOCTYPE html>
  <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>SSR React App</title>
      </head>
      <body>
          <div id="app">${html}</div>
          <script src="./app.min.js"></script>
      </body>
  </html>`

app.use(express.static(path.join(__dirname, 'dist')))

app.get('*', (req, res) => {
  let html = ReactDOMServer.renderToString(
    <App />
  )

  res.send(HTMLShell(html))
})

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

对于捆绑,我使用的是 Parcel。如何导入图像而不会出现此错误?

编辑:图像以这种方式导入:

import bgHeader from '../assets/bg.png'

4

0 回答 0