2

背景:一个简单的一页react app + redux + express(为了上传到heroku)。
我已经在公共文件夹中有 index.html 和 images 文件夹。我想运行 webpack 来生成我在 index.html 中使用的 styles.css 和 bundle.js。我想在每次运行构建时使用 webpack-clean-up-plugin 删除额外的先前文件,但我不希望这会影响 index.html 和 images 文件夹等内容。
根据文档: *Options 如果您想在输出路径中保留一些文件,例如从其他一些插件生成的 stats.json 文件,请使用 exclude Array 选项。它像在 minimatch 中一样接受 globbing。

// 不要删除stats.json, important.json, 和里面的所有东西folder

new WebpackCleanupPlugin({
  exclude: ["stats.json", "important.js", "folder/**/*"],
})

目标:运行 webpack.prod.js 所以最后公共文件夹有

  • 索引.html
  • 捆绑.js
  • bundle.js.map
  • 样式.css
  • 样式.css.map
  • 图片(文件夹)

Webpack.config.prod.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin')  
output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    }, 
    plugins: [
        new MiniCssExtractPlugin({ 
            filename: "styles.css", 
            chunkFilename: "[id].css"}),
         new CleanWebpackPlugin({
         exclude: ["index.html", "images/*"],
        })
      ],  

当前结果:
每次我 npm run

"build:prod": "webpack --config webpack.config.prod.js --mode production",

我会删除我的 index.html 和 images 文件夹。那我哪里写错了?

4

5 回答 5

4

而不是使用排除
使用此选项

cleanOnceBeforeBuildPatterns: ["**/*", "!stats.json","!important.js", "!folder/**/*"]

这对我有用:)。例子:

new CleanWebpackPlugin({
    root: process.cwd(),
    verbose: true,
    dry: false,
    cleanOnceBeforeBuildPatterns: ["**/*", "!stats.json","!important.js", "!folder/**/*"],
})
于 2020-03-26T06:08:28.650 回答
3

无论如何,在阅读更多内容后,我决定不再使用这个插件。因为人们一直在重复与我类似的问题。作者在 2018 年 3 月 22 日表示,他没有时间再维护了,我们应该关闭这个插件。 在 github 上查看这个

于 2019-06-26T10:28:48.227 回答
2

这可能是路径问题。你可以用 '__dirname' 解决它

于 2019-06-26T06:06:35.487 回答
1

您可以使用remove-files-webpack-plugin

配置:

plugins: [
  new RemovePlugin({
    before: {
      // expects what your output folder is `dist`.
      test: [
        {
          folder: './dist',
          method: () => true
        }
      ],
      exclude: [
        './dist/index.html',
        './dist/images'
      ]
    }
  })
]

注意:我是这个插件的创建者。

于 2020-02-26T21:02:38.917 回答
0

显然,未明确引用的文件被视为过时并被删除。这对我有用,可以跳过复制的清理文件CopyWebpackPlugin

new CleanWebpackPlugin({
   cleanStaleWebpackAssets: false,
}),
于 2020-09-04T17:29:49.013 回答