Vue.js / webpack: 当热加载传输编译它们时,如何清除旧的bundle main-*.js文件?

5
我正在使用Vue.js来制作一个SPA应用,配合Django使用。我使用webpack(具体来说是从vue-cli设置中选择的webpack-simple)来进行代码转换、压缩和打包。
我使用以下命令来"观察"并热重载代码:
$ ./node_modules/.bin/webpack --config webpack.config.js --watch

每次我更改代码并进行构建时,它都会生成一个新的文件并更新webpack-stats.json指向该文件,但不会删除旧文件。我该如何使其删除旧文件(无用文件)? webpack.config.js:
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')


function resolve (dir) {
    return path.join(__dirname, dir)
}

module.exports = {
    context: __dirname,

    // entry point of our app. 
    // assets/js/index.js should require other js modules and dependencies it needs
    entry: './src/main', 

    output: {
            path: path.resolve('./static/bundles/'),
            filename: "[name]-[hash].js",
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        }),
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
            {test: /\.vue$/, loader: 'vue-loader'}

        ],
    },

    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
}

webpack-stats.json:

{  
   "status":"done",
   "chunks":{  
      "main":[  
         {  
            "name":"main-faa72a69b29c1decd182.js",
            "path":"/Users/me/Code/projectname/static/bundles/main-faa72a69b29c1decd182.js"
         }
      ]
   }
}

此外,如何将此添加到git/source control是一个好方法?否则,每次更改都需要像这样添加:
$ git add static/bundles/main-XXXXX.js -f

这很令人烦恼。

有什么建议吗?谢谢!

3个回答

1
你需要使用 clean-webpack-pluginGithub链接
首先安装它:
npm i clean-webpack-plugin --save-dev

然后在webpack.config.js文件中添加以下内容(我已经添加了注释):

var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
const CleanWebpackPlugin = require('clean-webpack-plugin'); // require clean-webpack-plugin

function resolve (dir) {
    return path.join(__dirname, dir)
}

// the path(s) that should be cleaned
let pathsToClean = [
    path.resolve('./static/bundles/'),  // same as output path
]

// the clean options to use
let cleanOptions = {
    root: __dirname,
    exclude:  [],  // add files you wanna exclude here
    verbose:  true,
    dry:      false
}

module.exports = {
    context: __dirname,

    // entry point of our app. 
    // assets/js/index.js should require other js modules and dependencies it needs
    entry: './src/main', 

    output: {
        path: path.resolve('./static/bundles/'),
        filename: "[name]-[hash].js",
    },

    plugins: [
        new CleanWebpackPlugin(pathsToClean, cleanOptions),  // add clean-webpack to plugins
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            },
            sourceMap: true
        }),
    ],

    module: {
        loaders: [
            { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader'}, // to transform JSX into JS
            {test: /\.vue$/, loader: 'vue-loader'}

        ],
    },

    resolve: {
        extensions: ['.js', '.vue', '.json'],
        alias: {
            'vue$': 'vue/dist/vue.esm.js',
            '@': resolve('src')
        }
    },
}

就是这样,现在每次运行npm run build时,插件都会删除static/bundles/文件夹并进行构建,因此所有以前的文件都将被删除,只有新文件存在。在使用npm run watch监视时,它不会删除旧文件。


1

对于大多数情况,当前最新版本不需要传递任何选项。有关更多详细信息,请参阅文档 https://www.npmjs.com/package/clean-webpack-plugin

const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const webpackConfig = {
    plugins: [
        /**
         * All files inside webpack's output.path directory will be removed once, but the
         * directory itself will not be. If using webpack 4+'s default configuration,
         * everything under <PROJECT_DIR>/dist/ will be removed.
         * Use cleanOnceBeforeBuildPatterns to override this behavior.
         *
         * During rebuilds, all webpack assets that are not used anymore
         * will be removed automatically.
         *
         * See `Options and Defaults` for information
         */
        new CleanWebpackPlugin(),
    ],
};

module.exports = webpackConfig;

0

你应该调整webpack,只有在实际构建生产环境时才创建新的捆绑包。

从webpack-simple vue-cli模板中,你会发现只有在设置为生产环境而不是开发环境时,才进行代码压缩和缩小。

if (process.env.NODE_ENV === 'production') {
  module.exports.devtool = '#source-map'
  // http://vue-loader.vuejs.org/en/workflow/production.html
  module.exports.plugins = (module.exports.plugins || []).concat([
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"production"'
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      sourceMap: true,
      compress: {
        warnings: false
      }
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: true
    })
  ])
}

我认为这并没有解决他的问题。我相信主要的 main-.js 文件是在“watch”时生成的。他想自动删除包文件夹中的所有旧文件。 - Hanming Zeng

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