运行 webpack 时资产消失 --watch 如果修改了模板以外的文件

问题描述

我创建了一个小项目,它由一个 HTML 文件和一些资产(图像、视频、(S)CSS、JS)组成,我使用 webpack(所有已安装包的最新版本)来优化和捆绑这些文件。到目前为止,处理 SCSS 和 JS 文件的工作正常,但捆绑包含在 HTML 模板中的图像和视频无法按预期工作。

问题:当我执行 webpack --watch 时,图像/视频被正确复制到 dist 文件夹,但仅在第一次运行时。如果我修改例如SCSS 或 JS 文件,图像和视频从 dist 文件夹中消失,而 JS 和 CSS 文件正确生成/更新。如果我随后编辑 HTML 模板,图像/视频会重新出现在 dist 文件夹中。

我的代码中最相关的部分(请参阅下面的链接以查看/下载项目以便更轻松地重现问题):

// webpack.config.js

// ...
const config = {
  src: 'src/',dist: 'dist/',jsEntry: '/assets/js/main.js',cssEntry: '/assets/scss/main.scss',publicPath: '/',};

const absEntryPath = path.resolve(__dirname,config.src);
module.exports = {
  mode: 'production',entry: {
    style: absEntryPath + config.cssEntry,main: absEntryPath + config.jsEntry
  },output: {
    path: path.resolve(__dirname,config.dist),publicPath: config.publicPath,filename: 'assets/js/[name].[contenthash:4].min.js',clean: true
  },plugins: [
    new HtmlWebpackPlugin({
      template: config.src + 'index.ejs',cache: false,// ...
    }),new MiniCssExtractPlugin({
      filename: 'assets/css/[name].[contenthash:4].min.css'
    }),// ...
  ],module: {
    rules: [
      // ...
      {
        // html
        test: /\.(html|ejs)$/,exclude: /[\\/]node_modules[\\/]/,use: [
          {
            loader: 'html-loader',options: {
              sources: true,minimize: false,esModule: false
            }
          }
        ]
      },{
        // styles
        test: /\.(sa|sc|c)ss$/,use: [
           // ...
        ]
      },{
        // images
        test: /\.(jp(e)?g|png|gif)$/,use: {
          loader: 'file-loader',options: {
            esModule: false,name: '[name].[contenthash:4].[ext]',outputPath: 'assets/img/',publicPath: config.publicPath
          }
        }
      },{
        // video
        test: /\.(mp4|mov)$/,outputPath: 'assets/video/',// ...
    ]
  },// ...
};

<!-- /src/index.ejs -->
<!DOCTYPE html>
<html lang="en">
  <!-- ... -->
  <body>
    <div>
      <p>some image</p>
      <img src="./assets/img/some-image.jpg">
    </div>
    <div>
      <p>some video</p>
      <video controls poster="./assets/video/some-video_poster.png">
        <source src="./assets/video/some-video.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
  </body>
</html>

类似的行为已经在 herehere 中进行了描述,建议禁用 html-webpack-plugin 的缓存,但是正如您在我的 webpack.config.js 中看到的,我已经在使用cache: false 并没有解决问题。

作为一种解决方法,我目前正在从 dist 文件夹清理中排除图像/视频,但这迫使我保留由于可能的浏览器缓存问题而我并不真正想要的文件名。

问题:当我编辑 HTML 模板以外的文件时,如何防止图像/视频从 dist 文件夹中消失?我希望能够在文件名中使用哈希,而不必从 dist 文件夹清理中排除文件


我已将项目的精简版本上传到 Stackblitz,您可以在其中download。请注意,我没有专业帐户,因此无法上传图片/视频。如需复现问题,请将两张图片和视频替换到本地。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)