Webpack在手表上运行插件脚本

时间:2019-01-21 05:51:11

标签: javascript webpack watch webpack-watch

我为Webpack设置了一个处理应用程序文件和CSS的插件。

webpack.config.js

const path = require('path');
const glob = require('glob');
const uglify = require("uglify-js");
const cleanCSS = require("clean-css");
const merge = require('webpack-merge-and-include-globally');

const mode = 'dev';
const ext = mode === 'prod' ? '.min' : ''; 

module.exports = (event, arg) => {  

  let config = {

  mode: mode === 'dev' ? 'development' : 'prod' ? 'production' : '',
  entry: {
    bundle : [ "./build/index.js" ] 
  }, 
  output: {
    path: __dirname + '/public',
    filename: "js/[name].js"
  },
  plugins: [
    new merge({
        files: {
          // concatenate angular app
          './app/app.js' : [ 
            './build/app/js/app.js',
            './build/app/js/controllers/*',
            './build/app/js/directives/*', 
            './build/app/js/services/*', 
          ],
          // compile scripts & css 
          './js/scripts.js' : [ './build/js/scripts.js' ],
          './css/style.css' : [ './build/css/*' ]
        },
        transform: { // minify in prod mode
        './app/app.js' : code => mode === 'prod' ? uglify.minify(code).code : code,
        './js/scripts.js' : code => mode === 'prod' ? uglify.minify(code).code : code,
        './css/style.css' : code => mode === 'prod' ? new cleanCSS({}).minify(code).styles : code
      }
  })
]
}
return config; 
}

当我运行npm run build时,脚本将按预期的方式工作,以依赖关系构建bundle.js,以应用程序构建app.js,并以CSS构建style.css

但是,当我运行npm run watch时,webpack只监视bundle.js的入口文件-index.js。

是否可以指示webpack监视插件的入口文件?还是可以指出生成脚本是在更改某些任意文件时触发的?

1 个答案:

答案 0 :(得分:2)

我能够使用webpack-watch-files插件找到解决方案

const WatchExternalFilesPlugin = require('webpack-watch-files-plugin').default;

  new WatchExternalFilesPlugin({
    files: [
      './build/app/js/**/*.js',
      './build/js/*.js',
      './build/css/*.css',
      // '!./src/*.test.js'
    ]
  })

**注意:Webpack 4需要require语句中的.default