如何制作webpack的uglifyjs插件不会破坏sass的源地图?

时间:2016-11-21 16:08:03

标签: javascript webpack minify source-maps uglifyjs

以下是设置:

package.json

{
  "dependencies": {
    "css-loader": "^0.26.0",
    "extract-text-webpack-plugin": "^1.0.1",
    "html-webpack-plugin": "^2.24.1",
    "node-sass": "^3.13.0",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "webpack": "^1.13.3"
  }
}

webpack.config.js

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: './1.js',
    output: {
        path: 'dist',
        filename: 'bundle.js',
    },
    module: {
        loaders: [
            {test: /\.sass$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')},
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'template.ejs',
        }),
        new ExtractTextPlugin('[name].css'),
        new webpack.optimize.UglifyJsPlugin(),
    ],
    devtool: 'source-map',
};

template.ejs

<!doctype html>
<html>
<body>

<div></div>

</body>
</html>

1.js

require('./1.sass');

1.sass

body
    background: #ddd
div
    width: 100px
    height: 100px
    margin: auto
    background: #333

然后

$ rm -rf dist/* && ./node_modules/.bin/webpack

在Chrome中打开http://example.com/dist。然后转到Developer Tools&gt; Elements tab。点击div,然后点击div { width: 100px; ... }阻止的链接。并且你会发现自己在第2行。但是当你注释掉new webpack.optimize.UglifyJsPlugin()行时,你将按照预期排在第3行。我做错了什么?

1 个答案:

答案 0 :(得分:1)

首先要提到的是UglifyJsPlugin switches所有加载器都处于最小化模式。来自the docs

  

最小化块的所有JavaScript输出。 装载机切换到最小化模式。

但幸运的是,coming 2.x version已更改。

另一个问题是,当libsassoutputStyle时,compressed会生成wrong source map。如果您没有指定explicitly并且已启用缩小功能,outputStyle会被压缩。

因此,目前解决方法是指定除outputStyle以外的一些compressed

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
    entry: './1.js',
    output: {
        path: 'dist',
        filename: 'bundle.js',
    },
    module: {
        loaders: [
            {test: /\.sass$/, loader: ExtractTextPlugin.extract('style', 'css?sourceMap!sass?sourceMap')},
        ]
    },
    sassLoader: {
        outputStyle: 'nested',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'template.ejs',
        }),
        new ExtractTextPlugin('[name].css'),
        new webpack.optimize.UglifyJsPlugin(),
    ],
    devtool: 'source-map',
};

UPD 最有可能source-map包和css-loader包也存在问题。因此,您可以考虑禁用缩小,例如:css?sourceMap&-minimize