React服务器端渲染与Webpack的比较

4

我是服务器端React渲染的新手,我可以使用webpack为客户端和Express为服务器端(当然是通过React)创建简单的同构React应用程序。但现在我遇到了一些问题 - 我决定在我的项目中使用图片:

export default class JustImage extends Component {
  render() {
    return (
      <div>
        <img src={require("just_image.png")} />
      </div>
    );
  }
}

客户端的代码运行良好,但当我尝试呈现服务器端代码时,出现以下错误:

just_image.png: Unexpected character '�'

据我了解,Node.js对webpack加载程序一无所知,因此无法正确加载图像。由于我对React和服务器端渲染都很陌生,我想知道是否有任何标准方法来解决这个问题 - 不仅仅是图像,我还使用图像(PNG / JPEG / JPG / ICO),SVG,SASS / LESS / CSS。提前感谢。

2个回答

3

据我所知,解决这个问题有两种方法:

  1. Use the webpack for your server code as well. In your webpack configuration for server, you can use the same loader you did for your client. For example, you can use url-loader or file-loader for image files.

    {
      test: /\.(jpe?g|png|gif|svg)$/i,
      loader: 'url-loader',
      options: {
        limit: 8192,
      },
    }
    
  2. You can hack the require.extensions at the top of your server code.

    if (process.env === 'development') {
      require.extensions['.png'] = () => {}
    }
    

我在这里发布了一个类似的问题(链接),但没有得到回答 :)


谢谢回答。但我不明白如何在服务器端使用webpack。请给我一些示例。 - malcoauri
2
start脚本可以是webpack --watch --config config/your-server-config.js && babel-node dist/server.js。对于我的个人项目,我选择了第二个选项,因为每次代码更改重新打包服务器代码需要一些时间,不适合开发。有关示例代码/配置,请访问https://github.com/ming-soon/mern-starter。 - Ming Soon
1
不,它没有任何副作用,除了你必须在服务器代码的最开始添加上述代码。 - Ming Soon
@MingSoon 如果我添加这个 'require' 并且在图像标签的 src 属性中使用一些图像,我的代码将会出错。 - malcoauri
@Mateusz,请给我链接,我不知道SSR是什么意思。 - malcoauri
显示剩余4条评论

0

我通过阅读react-starter-kit的代码学到了很多,基本上就是Ming Soon告诉你的,你需要使用webpack编译你的服务器端代码,你需要多个webpack配置文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接