删除未使用的webpack块文件

Delete unused webpack chunked files

本文关键字:文件 webpack 未使用 删除      更新时间:2023-09-26

我正在寻找有关如何删除旧的webpack块文件的信息。以下是我当前的webpack配置:

var path = require('path');
var webpack = require('webpack');
module.exports = {
  debug: false,
  outputPathinfo: true,
  displayErrorDetails: true,
  context: __dirname,
  entry: {
    common: ['./src/common.coffee'],
    a: './src/a.cjsx',
    b: './src/b.cjsx'
  },
  output: {
    filename: '[name]-[chunkhash].js',
    chunkFileName: '[name].[chunkhash].js',
    path: path.join(__dirname, 'js')
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin('common', 'common-[chunkhash].js'),
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false }
    })
  ],
  module: {
    preLoaders: [
      {
        test: /'.coffee$/,
        exclude: /node_modules/,
        loader: 'coffeelint-loader'
      }
    ],
    loaders: [
      { test: /'.coffee/, loader: 'coffee' },
      { test: /'.cjsx$/, loaders: ['coffee', 'cjsx'] },
      { test: /'.js$/, loader: 'jsx-loader?harmony' }
    ]
  }
}

如果我正在运行$(npm bin)/webpack --config webpack.js --watch并对a.cjsx进行更改,它将编译该文件的新版本,并使用新的块列。但是,旧的那个还在,我希望它马上被删除。

  1. 如何删除旧版本的分块文件?
  2. 有一种方法让我挂钩到一个后回调手表完成编译?

有一个clean-webpack-plugin用于这些目的,或者您可以为npm编写一个简单的bash脚本:

 "scripts": {
    "build": "rm -r dist/* && webpack -p",
    "clean": "rm -r dist/*"
  }

这是webpack-clean-obsolete-chunks插件,它做你想做的。它在每次webpack编译后搜索所有更新的块并删除过时的文件。

答案

我决定写一个答案,因为其他人虽然试图直接回答这个问题,但却忽略了我认为最重要的部分。

最重要的部分是:你不应该这样做。在您的开发设置中使用[hash]占位符会导致许多其他工具(例如phpstorm在symfony插件中的路径自动完成)的麻烦。此外,它对webpack的增量编译性能也很差,因此官方webpack文档(参考)不推荐使用。

因此,对于未来的读者:只需保持简单的开发配置-将filename定义为[name].js,然后继续。

编辑

对于如何处理生产服务器上的旧块文件似乎有些困惑。你什么都不做。一旦部署了一个版本,就不应该对它进行任何更改。您只需在部署时不断创建新版本,并保留旧版本作为备份。为什么?

因为你希望你的回滚是可靠的,而为了使它成为可能,你的回滚需要非常简单和原子化。如果您的回滚过程所做的不仅仅是切换符号链接、重新路由到上一个容器(或类似的简单操作),那么您可能会遇到麻烦。

回滚不是再次"重新部署"应用程序的过程,而是现在到以前的版本。这是一个"撤销"部署的过程。所以做一个git checkout到以前的版本,然后是一个npm build --but-please-be-hurry --and-im-begging-you-dont-fail,而你的生产应用程序挂在那里,完全爆炸不削减这里。

重新构建以前版本的应用程序——就像部署一样——可能会由于许多原因而失败。这就是回滚应该切换/重新路由到被证明有效的完全相同的版本构建的原因。不是== -the-same, 100% === -the-same。这就是为什么您需要保留以前的版本,因为这是===相同的。在最好的情况下,"再生"的一个只有==相同,所以它不能被证明是有效的,只是假设。

不,再多的CI、登台环境或任何东西都不能保证成功部署。做正确的事情的一部分是为事情出错做好准备。事情出错。希望只是偶尔,但仍然。

当然,一旦你备份了3、5或<put-your-number-here>版本,你可能会开始删除最旧的版本,因为你可能永远不需要超过3个。

从Webpack 5.20.0开始,你可以使用output.clean选项

看看这个pull request:https://github.com/johnagan/clean-webpack-plugin/pull/32/files

打开原始文件视图并将其复制到clean webpack插件的index.js中。请记住config flag -> watch: true

我已经通过在webpack.config.js

中添加下面的内容解决了这个问题
const { CleanWebpackPlugin } = require('clean-webpack-plugin');    
{
  ... your configs ...
  plugins: [new CleanWebpackPlugin()]
}

您可以通过使用remove-files-webpack-plugin来解决问题。

像这样使用插件:

plugins: [
  new RemovePlugin({
    watch: {
      test: [
        {
          folder: './js',
          method: (absPath) => new RegExp(/(.*)-([^-'''/]+)'.js/).test(absPath)
        }
      ]
    }
  })
]

在"watch"模式下(不是正常编译!),它从./js文件夹中抓取所有文件,并用这个正则表达式/(.*)-([^-'''/]+)'.js/测试它们。如果在理解上有问题,请在regex101上分析这个正则表达式(包括单元测试)。

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

看起来webpack@5.20.0+对此有内置支持https://webpack.js.org/configuration/output/#outputclean。我在我的块文件名中使用[chunkhash],如果我停止注释动态导入,它们会被清除,如果我取消注释,它们会被添加回来。

my case: webpack 5 + multipage application + themes.css via entry points

解决方案:https://github.com/webdiscus/webpack-remove-empty-scripts

这个插件不能与webpack 5入口点或MiniCssExtractPlugin一起工作:

webpack-fix-style-only-entries,webpack-extraneous-file-cleanup-plugin,webpack-remove-empty-js-chunks-plugin,webpack-delete-no-js-entries-plugin .

my webpack.config.js:

const fs = require('fs');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const RemoveEmptyScriptsPlugin = require('webpack-remove-empty-scripts');
const isProd = process.env.NODE_ENV === 'production';
const isDev = !isProd;
const PAGES = ['app', 'help'];
const getThemes = (themePath, alias) => {
  let themes = {};
  const longPath = './' + alias + '/' + themePath;
  fs.readdirSync(longPath).forEach(function(fileName) {
    const fileNameWithPath = path.join(themePath, fileName);
    const fileNameWithLongPath = path.join(longPath, fileName);
    const stat = fs.lstatSync(fileNameWithLongPath);
    if (stat.isDirectory()) return;
    if (!/'.scss$/.test(fileName)) return;
    const nameWithoutExt = path.basename(fileName, '.scss');
    themes[nameWithoutExt] = ['./' + fileNameWithPath];
  });
  console.log(themes);
  return themes;
};
const themes = getThemes('scss/themes', 'src');
const getFilename = (filename, ext) => {
  let name = filename == 'index' ? 'bundle' : filename;
  const isTheme = (ext == 'css' && name.startsWith('theme')) ? true : false;
  const needHash = (isDev || isTheme) ? false : true;
  return needHash ? name +`.[fullhash].` + ext : name+'.'+ext;
};
const getCSSDirname = filename => {
  const isTheme = filename.startsWith('theme');
  return !isTheme? '/css/' : '/css/theme/';
};
const getHTMLWebpackPlugins = arr => {
  // this function config multipages names and add to html-pages
  // inside <head> tag our themes via tag <link rel="stylesheet" href="....css" ...>
  // and return array of HTMLWebpackPlugins
};
module.exports = {
// ... //
  entry: {
    // mutipage:
    app:  ['./index.js', './scss/app.scss'], 
    help: ['./help.js', './scss/help.scss'],
    // multitheme:
    ...themes,
  },
  optimization: {
    removeEmptyChunks: true, // not work!!!
  },
  // ... //
  plugins: [
    // ... //
    ...getHTMLWebpackPlugins(PAGES),
    new RemoveEmptyScriptsPlugin({
      ignore:  PAGES,
      enabled: isDev === false,
    }),
    new MiniCssExtractPlugin({
      filename: pathdata => {
        return getCSSDirname(pathdata.chunk.name) + getFilename(pathdata.chunk.name, 'css');
      },
      chunkFilename: isDev ? '[id].css' : '[id].[contenthash].css',
    }),
  ],
};

my SRC files:

[src]:
 - index.js
 - index.html
 - help.js
 - help.html
 - [scss]:
 - - app.scss
 - - help.scss
 - - [themes]:
 - - - light.scss
 - - - dark.scss
 - - - blue.scss
构建后

:

[dist]:
 - app.js
 - index.html
 - help$hash.js
 - help$hash.html
 - [css]:
 - - app$hash.css
 - - help$hash.css
 - - [themes]:
 - - - light.css
 - - - dark.css
 - - - blue.css

Windows用户

  "scripts": {
    "build": "npm run clean && webpack --mode production",
    "clean": "del /f /s /q dist 1>nul"
  }

我不得不停止我的服务器并再次运行yarn serve