简体   繁体   中英

Vue.js / webpack: how do I clear out old bundle main-*.js files when hot-reload transpiles them?

I'm using Vue.js to make an SPA application with Django and I transpile, uglify, and bundle the code using webpack (specifically webpack-simple from vue-cli setup).

I use the following to "watch" and hot-reload the code:

$ ./node_modules/.bin/webpack --config webpack.config.js --watch

The problem is every time I change the code and it gets built it generates a new bundle .js file and updates webpack-stats.json to point to that one, but doesn't delete the old ones. How do I have it delete the old (useless) files?

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"
         }
      ]
   }
}

Also what's a good way to add this to git/source control? Otherwise it changes everytime and I have to add it like so:

$ git add static/bundles/main-XXXXX.js -f

which gets annoying.

Any pointers? Thanks!

You need clean-webpack-plugin github link
First install it:

npm i clean-webpack-plugin --save-dev

Then in webpack.config.js add these lines(I have added comments the lines I added):

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')
        }
    },
}

And that's it, now every time you will run npm run build , the plugin will delete the static/bundles/ folder then build, so all your previous files will get removed, only new files will be there. It won't remove old files while watching with npm run watch

The current latest version does not need any options passed in for most cases. Consult the documentation for more specifics 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;

You should adjust webpack so a new bundle is only being created when actually building for production.

From the webpack-simple vue-cli template, you'll see that uglifying and minifying only take place when it is set to a production env, not a dev env:

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
    })
  ])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM