在webpack中可以配置watch监听器时时打包:

  • 1、配置如下:
module.exports = {
    watch: true,
    watchOptions: {
      poll: 1000, // 每秒询问多少次
      aggregateTimeout: 500,  //防抖 多少毫秒后再次触发
      ignored: /node_modules/ //忽略时时监听
    }
}

webpack.config.js完整配置:

//  webpack是node写出来的, 需要node的写法
let path = require('path');
// path.resolve 相对路径转成绝对路径
// console.log(path.resolve('dist'));
// 以当前目录
// console.log(__dirname);

// html-webpack-plugins 插件
let HtmlWebpackPlugins = require('html-webpack-plugin');


// webpack相关配置
module.exports = {
    // 开发服务的配置
    devServer: {
        // 端口,默认8080
        port: '8099',
        // 进度条
        progress: true,
        // 启动后访问目录,默认是项目根目录,这个设置到打包后目录
        contentBase: './build',
        // 启动压缩
        //compress: true
    },
    // 模式,2种:生产模式(production)和开发模式(development)
    // 开发模式不压缩打包后代码,生产模式压缩打包后代码
    mode: 'production',
    // 1、source-map:产生文件,产生行列
    // devtool: 'source-map',
    // 2、eval-source-map:不产生文件,产生行类
    //devtool: 'eval-source-map',
    // 3、cheap-source-map:产生文件,不产生列
    //devtool: 'cheap-module-source-map',
    // 4、cheap-module-eval-source-map:不产生文件,不产生列
    //devtool: 'cheap-module-eval-source-map',

    // 监听
    watch: true,
    watchOptions: {
        poll: 1000, // 每秒询问多少次
        aggregateTimeout: 500,  //防抖 多少毫秒后再次触发
        ignored: /node_modules/ //忽略时时监听
    },

    // 入口,表示从哪里开始打包
    entry: {
        home: './src/index.js'
    }, 
    // 表示出口(输出后文件相关配置)
    output: {   
        // 打包后的文件名 多入口根据入口名称生成
        filename: 'build.js',  
        // 输出后的路径(必须是一个绝对路径)
        path: path.resolve(__dirname, 'dist')
    },
    // 插件配置
    plugins: [
        new HtmlWebpackPlugins({
            // 模板位置
            template: 'index.html',
            // 文件名
            filename: 'index.html'
        })
    ],
    module: {
        // loader
        rules: [
            {
                test: /\.js$/, //匹配js文件
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env'
                        ]
                    }
                }
            }
        ]
     }
}