Javascript 如何使用 webpack 构建缩小和未压缩的包?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25956937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:08:20  来源:igfitidea点击:

How to build minified and uncompressed bundle with webpack?

javascriptnode.jswebpack

提问by Thank you

Here's my webpack.config.js

这是我的 webpack.config.js

var webpack = require("webpack");

module.exports = {

  entry: "./entry.js",
  devtool: "source-map",
  output: {
    path: "./dist",
    filename: "bundle.min.js"
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({minimize: true})
  ]
};

I'm building with

我正在建设

$ webpack

In my distfolder, I'm only getting

在我的dist文件夹中,我只得到

  • bundle.min.js
  • bundle.min.js.map
  • bundle.min.js
  • bundle.min.js.map

I'd also like to see the uncompressed bundle.js

我也想看未压缩的 bundle.js

采纳答案by Estus Flask

webpack.config.js:

webpack.config.js:

const webpack = require("webpack");

module.exports = {
  entry: {
    "bundle": "./entry.js",
    "bundle.min": "./entry.js",
  },
  devtool: "source-map",
  output: {
    path: "./dist",
    filename: "[name].js"
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      include: /\.min\.js$/,
      minimize: true
    })
  ]
};

Since Webpack 4, webpack.optimize.UglifyJsPluginhas been deprecated and its use results in error:

自 Webpack 4 起,webpack.optimize.UglifyJsPlugin已被弃用,其使用会导致错误:

webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead

webpack.optimize.UglifyJsPlugin 已被移除,请改用 config.optimization.minimize

As the manualexplains, the plugin can be replaced with minimizeoption. Custom configuration can be provided to the plugin by specifying UglifyJsPlugininstance:

正如手册所解释的,插件可以替换为minimize选项。可以通过指定UglifyJsPlugin实例为插件提供自定义配置:

const webpack = require("webpack");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  // ...
  optimization: {
    minimize: true,
    minimizer: [new UglifyJsPlugin({
      include: /\.min\.js$/
    })]
  }
};

This does the job for a simple setup. A more effective solution is to use Gulp together with Webpack and do the same thing in one pass.

这可以完成简单设置的工作。一个更有效的解决方案是将 Gulp 与 Webpack 一起使用,并一次性完成相同的事情。

回答by lyosef

You can use a single config file, and include the UglifyJS plugin conditionally using an environment variable:

您可以使用单个配置文件,并使用环境变量有条件地包含 UglifyJS 插件:

var webpack = require('webpack');

var PROD = JSON.parse(process.env.PROD_ENV || '0');

module.exports = {

  entry: './entry.js',
  devtool: 'source-map',
  output: {
    path: './dist',
    filename: PROD ? 'bundle.min.js' : 'bundle.js'
  },
  plugins: PROD ? [
    new webpack.optimize.UglifyJsPlugin({
      compress: { warnings: false }
    })
  ] : []
};

and then just set this variable when you want to minify it:

然后在你想缩小它时设置这个变量:

$ PROD_ENV=1 webpack


Edit:


编辑:

As mentioned in the comments, NODE_ENVis generally used (by convention) to state whether a particular environment is a production or a development environment. To check it, you can also set var PROD = (process.env.NODE_ENV === 'production'), and continue normally.

正如评论中提到的,NODE_ENV通常(按照惯例)用于说明特定环境是生产环境还是开发环境。要检查它,您也可以设置var PROD = (process.env.NODE_ENV === 'production'),然后正常继续。

回答by Gordon Freeman

You can run webpack twice with different arguments:

您可以使用不同的参数运行 webpack 两次:

$ webpack --minimize

then check command line arguments in webpack.config.js:

然后检查命令行参数webpack.config.js

var path = require('path'),
  webpack = require('webpack'),
  minimize = process.argv.indexOf('--minimize') !== -1,
  plugins = [];

if (minimize) {
  plugins.push(new webpack.optimize.UglifyJsPlugin());
}

...

example webpack.config.js

示例webpack.config.js

回答by everett1992

To add another answer, the flag -p(short for --optimize-minimize) will enable the UglifyJS with default arguments.

要添加另一个答案,标志-p( 的缩写--optimize-minimize)将使用默认参数启用 UglifyJS。

You won't get a minified and raw bundle out of a single run or generate differently named bundles so the -pflag may not meet your use case.

您不会从单次运行中获得缩小的原始包,-p也不会生成不同名称的包,因此该标志可能不符合您的用例。

Conversely the -doption is short for --debug--devtool sourcemap--output-pathinfo

相反,该-d选项的缩写为--debug--devtool sourcemap--output-pathinfo

My webpack.config.js omits devtool, debug, pathinfo, and the minmize plugin in favor of these two flags.

我的 webpack.config.js 省略了devtool, debug,pathinfo和 minmize 插件以支持这两个标志。

回答by Howard

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-pluginfor this purpose.

也许我来晚了,但我有同样的问题,所以我为此编写了一个unminified-webpack-plugin

Installation

安装

npm install --save-dev unminified-webpack-plugin

Usage

用法

var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^

通过以上操作,您将获得两个文件 library.min.js 和 library.js。无需执行 webpack 两次,它就可以工作!^^

回答by Dave Kerr

In my opinion it's a loteasier just to use the UglifyJStool directly:

在我看来,这是一个很多更容易只是使用UglifyJS直接的工具:

  1. npm install --save-dev uglify-js
  2. Use webpack as normal, e.g. building a ./dst/bundle.jsfile.
  3. Add a buildcommand to your package.json:

    "scripts": {
        "build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
    }
    
  4. Whenever you want to build a your bundle as well as uglified code and sourcemaps, run the npm run buildcommand.
  1. npm install --save-dev uglify-js
  2. 正常使用 webpack,例如构建./dst/bundle.js文件。
  3. build命令添加到您的package.json

    "scripts": {
        "build": "webpack && uglifyjs ./dst/bundle.js -c -m -o ./dst/bundle.min.js --source-map ./dst/bundle.min.js.map"
    }
    
  4. 每当您想要构建您的包以及丑陋的代码和源映射时,请运行该npm run build命令。

No need to install uglify-js globally, just install it locally for the project.

无需全局安装 uglify-js,只需为项目本地安装即可。

回答by trekforever

You can create two configs for webpack, one that minifies the code and one that doesn't (just remove the optimize.UglifyJSPlugin line) and then run both configurations at the same time $ webpack && webpack --config webpack.config.min.js

您可以为 webpack 创建两个配置,一个缩小代码,一个不缩小(只需删除 optimize.UglifyJSPlugin 行),然后同时运行这两个配置 $ webpack && webpack --config webpack.config.min.js

回答by Ideabile

According with this line: https://github.com/pingyuanChen/webpack-uglify-js-plugin/blob/master/index.js#L117

根据这一行:https: //github.com/pingyuanChen/webpack-uglify-js-plugin/blob/master/index.js#L117

should be something like:

应该是这样的:

var webpack = require("webpack");

module.exports = {

  entry: "./entry.js",
  devtool: "source-map",
  output: {
    path: "./dist",
    filename: "bundle.js"
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
     minimize: true,
     compress: false
    })
  ]
};

Indeed you can have multiple builds by exporting different configs according your env / argv strategies.

实际上,您可以通过根据您的 env / argv 策略导出不同的配置来进行多个构建。

回答by gdfgdfg

webpack entry.jsx ./output.js -p

webpack entry.jsx ./output.js -p

works for me, with -pflag.

对我有用,带-p标志。

回答by cnzac

You can format your webpack.config.js like this:

你可以像这样格式化你的 webpack.config.js:

var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');

module.exports = {
    context: __dirname,
    devtool: debug ? "inline-sourcemap" : null,
    entry: "./entry.js",
    output: {
        path: __dirname + "/dist",
        filename: "library.min.js"
    },
    plugins: debug ? [] : [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(),
        new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
    ],
};'

And then to build it unminified run (while in the project's main directory):

然后构建它未缩小的运行(在项目的主目录中):

$ webpack

To build it minified run:

要构建它缩小运行:

$ NODE_ENV=production webpack

Notes: Make sure that for the unminified version you change the output file name to library.jsand for the minified library.min.jsso they do not overwrite each other.

注意:确保对于未缩小版本,您将输出文件名更改为library.js和 缩小版本,library.min.js以便它们不会相互覆盖。