一个webpack的例子
2017/08/03    标签: webpack打包   
//http://www.css88.com/doc/webpack2/plugins/commons-chunk-plugin/
//http://www.zhufengpeixun.com/qianduanjishuziliao/Nodejishuziliao/2017-01-17/693.html
//https://webpack.js.org/
var Path = require('path');
var Webpack = require('webpack');
module.exports = {
    watch: true,//修改自动编译
    watchOptions: {
        aggregateTimeout: 1000,
        poll: 10
    },
    devtool: 'source-map',
    entry: {//字符串数组对象、建议为对象
        init:['./scripts/init.js'],
        common: ['./scripts/file.min.js','./scripts/md5.js'],
        user:['./scripts/file.min.js']
    },
    externals: {
        'jquery':'jQuery' //打包的时候不会被打包到文件里,需要在页面内单独引入,jquery是require时的名字,jQuery是window全局变量 
    },
    output: {
        path: Path.resolve(__dirname, './scripts/dist'),
        filename: '[name].js', //生成对应entry关键字的文件
        libraryTarget:'umd' //umd规范打包
    },
    plugins:[
        new Webpack.optimize.CommonsChunkPlugin({
            name:["common","user","init"],//对入口文件,分别进行压缩,entry对象下键名;数组最后一个对应生成的文件,最先引入,否则报错“file3.js:1 Uncaught ReferenceError: webpackJsonp is not defined”
            filename:'[name].js'
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
            warnings: false,
            drop_console: true //是否去除console输出
            }
        })
    ]
}

将以上代码保存在项目根目录下/webpack.config.js

(注:webpack全局安装 [只为使用webpack命令,并不能require到],且在项目所在盘符根目录安装webpack[这样就可以require到]为了保持项目的干净,并不安装到每个项目)。

打开cmd切换到根目录并运行命令

webpack --config webpack.config.js



另一种监控文件变化,然后进行webpack编译的方法

/***
    需要全局安装webpack和gaze
***/
var Gaze = require('gaze').Gaze;
var gaze = new Gaze(['./scripts/**/*.js', './styles/**/*.css']);
var path = require('path');
var cp = require('child_process');
var cpExec= function(cmd) {
    cp.exec(cmd,
        function(err, stdout, stderr) {
            var rst = '';
            if (err) {
                console.log(err);
            }
            if (stdout) {
                rst = stdout.replace(/\\n/g, '\n');
                console.log(rst);
            }
            if (stderr) {
                rst = stderr.replace(/\\n/g, '\n');
                console.log(rst);
            }
        });
};
gaze.on('all',
    function (event, filepath) {
        var pathExtName = path.extname(filepath);
        switch (pathExtName) {
            case '.ts':
            case '.scss':
            case '.css':
            {
                cpExec('webpack --config webpack.config.js');
            }
            break;
            case '.js':
            {
                    console.log(filepath);
                    console.log(/scripts\\dist\\bundle.js/.test(filepath));
                    if (/scripts\\dist\\bundle.js/.test(filepath) == false) {
                        cpExec('webpack --config webpack.config.js');
                    }
                }
        }
    });

将文件保存在和webpack.config.js同目录下/webpack.watch.js

运行cmd命令:

node webpack.watch.js