External source maps for minified, transpiled ES6 code with webpack and gulp

前端 未结 2 2036
孤街浪徒
孤街浪徒 2021-02-05 04:44

I\'m writing ES6 code and transpile it to ES5 with Babel, then minify with Uglify. All run with webpack via gulp. I would like to use external source maps (to keep filesize as s

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-05 05:28

    I highly recommend putting your webpack config inside the gulpfile, or at least make it a function. This has some nice benefits, such as being able to reuse it for different tasks, but with different options.

    I also recommend using webpack directly instead of using gulp-webpack (especially if it's the only thing you're piping through). This will give much more predictable results, in my experience. With the following configuration, source maps work fine for me even when UglifyJS is used:

    "use strict";
    
    var path = require("path");
    var gulp = require("gulp");
    var gutil = require("gulp-util");
    var webpack = require("webpack");
    
    function buildJs (options, callback) {
        var plugins = options.minify ? [
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false,
                },
    
                output: {
                    comments: false,
                    semicolons: true,
                },
            }),
        ] : [];
    
        webpack({
            entry: path.join(__dirname, "src", "index.js"),
            bail: !options.watch,
            watch: options.watch,
            devtool: "source-map",
            plugins: plugins,
            output: {
                path: path.join(__dirname, "dist"),
                filename: "index.js",
            },
            module: {
                loaders: [{
                    loader: "babel-loader",
                    test: /\.js$/,
                    include: [
                        path.join(__dirname, "src"),
                    ],
                }],
            },
        }, function (error, stats) {
            if ( error ) {
                var pluginError = new gutil.PluginError("webpack", error);
    
                if ( callback ) {
                    callback(pluginError);
                } else {
                    gutil.log("[webpack]", pluginError);
                }
    
                return;
            }
    
            gutil.log("[webpack]", stats.toString());
            if (callback) { callback(); }
        });
    }
    
    gulp.task("js:es6", function (callback) {
        buildJs({ watch: false, minify: false }, callback);
    });
    
    gulp.task("js:es6:minify", function (callback) {
        buildJs({ watch: false, minify: true }, callback);
    });
    
    gulp.task("watch", function () {
        buildJs({ watch: true, minify: false });
    });
    

提交回复
热议问题