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

Posted

技术标签:

【中文标题】Vue.js / webpack:当热重载编译它们时,如何清除旧的包 main-*.js 文件?【英文标题】:Vue.js / webpack: how do I clear out old bundle main-*.js files when hot-reload transpiles them? 【发布时间】:2017-11-03 04:53:46 【问题描述】:

我正在使用 Vue.js 使用 Django 创建一个 SPA 应用程序,并使用 webpack 转换、丑化和捆绑代码(特别是来自 vue-cli 设置的 webpack-simple)。

我使用以下代码“观看”并热重载代码:

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

问题是每次我更改代码并构建它时,它都会生成一个新的 bundle .js 文件并更新 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/源代码控制中?否则它每次都会改变,我必须像这样添加它:

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

这很烦人。

有什么建议吗?谢谢!

【问题讨论】:

【参考方案1】:

你需要clean-webpack-plugingithub link 首先安装它:

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

然后在 webpack.config.js 中添加这些行(我已经添加了我添加的行的 cmets):

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观看时不会删除旧文件

【讨论】:

【参考方案2】:

当前最新版本在大多数情况下不需要传入任何选项。有关更多详细信息,请参阅文档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;

【讨论】:

【参考方案3】:

您应该调整 webpack,以便仅在实际构建生产环境时创建新包。

从 webpack-simple vue-cli 模板中,您会看到只有在将其设置为生产环境而不是开发环境时才会进行 uglifying 和缩小:

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”上生成的。他想自动删除捆绑文件夹中的所有旧文件

以上是关于Vue.js / webpack:当热重载编译它们时,如何清除旧的包 main-*.js 文件?的主要内容,如果未能解决你的问题,请参考以下文章

由搭建Vue.js了解webpack,vue-loader和热重载

sh 配合Vue.js配置Webpack - 20. webpack监听文件变动进行自动编译的--watch

Webpack 开发服务器不热重载 .vue 文件

sh 配合Vue.js配置Webpack - 34. Babel的编译报错信息

Webpack 使用 NODE_ENV=production 编译 vue 仍然会导致开发警告

Webpack:热重载不起作用,但更改编译