首页 > 解决方案 > nuxt 中的图像 require() 由 HRM webpack 热重载

问题描述

我在项目导航栏中的 nuxt :src="require('path/to/image' + dynamic.variable)" 中使用 vue-webpack 图像的动态源。如果用户通过重新获取他们的信息并删除他们以前的图像的表单替换他们的图像,我得到一个 webpack 错误模块 (img) not found(它没有找到新的):有没有办法解决这个问题,比如等待webpack HRM 完成?

我尝试在用户重新获取之前设置一秒的 setTimeout() 并且它可以工作,但我不喜欢随机等待,我会使用承诺或同步动态,关键是 webpack 热重载不受控制通过我的功能..我也尝试将动态路径设置为计算:但它没有修复。

我的图片标签:

<img v-if="this.$auth.user.image" class="userlogo m-2 rounded-circle" :src="require('@assets/images/users/' + this.$auth.user.image)" alt="usrimg">

我的 Useredit 页面方法:

...
methods: {
    userEdit() {
      //uploads the image
      if (this.formImageFilename.name) {
        let formImageData = new FormData()
        formImageData.append('file', this.formImageFilename)
        axios.post('/db/userimage', formImageData, { headers: { 'Content-Type': 'multipart/form-data' } })
        // once it has uploaded the new image, it deletes the old one 
        .then(res=>{this.deleteOldImage()})
        .catch(err=>{console.log(err)})
      }else{
        this.userUpdate() //if no new image has to be inserted, it proceeds to update the user information
      }
    },
    deleteOldImage(){
      if(this.$auth.user.image){axios.delete('/db/userimage', {data: {delimage: this.$auth.user.image}} )}
      console.log(this.$auth.user.image + ' deleted')
      this.userUpdate() // it has deleted the old image so it proceeds to update the user information
    },
    userUpdate(){
      axios.put(
        '/db/user', {
          id: this.id,
          name: this.formName,
          surname: this.formSurname,
          email: this.formEmail,
          password: this.formPassword,
          image: this.formImageFilename.name,
        })
      .then(() => { console.log('User updated'); this.userReload()}) // reloads the updated user information
      .catch(err => {console.log(err)} )
    },
    userReload(){
      console.log('User reloading..')
      this.$auth.fetchUser()
      .then(() => { console.log('User reloaded')})
      .catch(err => {console.log(err)} )
    },
  }
...

问题发生在“console.log('User reloading..')”之后和“console.log('User reloaded');”之前,它与文件上传和服务器响应无关。我在许多小程序中破坏了一个函数,只是为了检查函数进程及其异步动态,但唯一无法管理的是 webpack 热重载:/

我希望用户上传他们的图片,并在提交表单后看到他们在导航栏中的徽标出现更新。

标签: vue.jswebpacknuxt.js

解决方案


首先,正如有人在评论中告诉你的那样,webpack hmr 不应该用于生产。

在 Nuxt 中,您从 assets 文件夹中引用的所有内容都将被优化并捆绑到项目包中。所以这个文件夹的理想用例是所有可以打包和优化的资产,并且很可能不会改变,如字体、css、背景图像、图标等。

然后,当 webpack 为本地开发构建站点或构建站点以生成生产包时,require 仅被调用一次。您的问题是您在开发过程中删除了原始文件,而 webpack 尝试读取它并失败。

对于用户上传的这些图像,我认为您应该使用 静态文件夹而不是使用 require 您必须更改 :src 与

:src="'/images/users/' + this.$auth.user.image"

让我知道这是否有帮助。


推荐阅读