webpack-如何同时输出压缩和未压缩的文件

有的时候我们想要同时生成压缩和未压缩的文件,比如我们构建 lib 包的时候,我们希望用户能够使用压缩过后的代码文件作为 cdn 文件,最简单的一个方式就是通过指定环境变量,比如指定 MINIFY,如下:


const path = require('path')

const isMinify = process.env.MINIFY

/**
 * @type {import('webpack').Configuration}
 */
const config = {
  entry: {

    index: './src/index.js'
  },
  output: {
    filename: isMinify ? '[name].min.js' : '[name].js',
    path: path.join(__dirname, 'dist')
  },
  devtool: 'cheap-source-map',
  optimization: {
    minimize: isMinify ? true : false
  }
}

module.exports = config

我们在使用的时候通过指定环境变量就可以打包成不同的版本:

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build:min": "MINIFY=1 webpack --config=webpack.config.js",
    "build": "webpack --config=webpack.config.js"
  }

不过这样的缺点就是我们需要运行两次。

第二个方法是安装 unminified-webpack-plugin,通过这个插件可以生成没有压缩的文件:


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

/**
 * @type {import('webpack').Configuration}
 */
const config = {
  entry: {
    index: './src/index.js',
  },
  output: {
    filename: '[name].min.js',
    path: path.join(__dirname, 'dist')
  },
  devtool: 'cheap-source-map',
  plugins: [
    new UnminifiedWebpackPlugin({})
  ]
}

module.exports = config

不过这个有个缺点就是未压缩的文件没有 sourcemap。

第三种方法通过指定多个打包入口,然后手动指定压缩插件(uglifyjs、terser等)压缩哪些文件,如我们指定 index.min.js 这个文件才需要压缩,配置如下:


const path = require('path')
const TerserWebpackPlugin = require('terser-webpack-plugin');

/**
 * @type {import('webpack').Configuration}
 */
const config = {
  entry: {
    index: './src/index.js',
    'index.min': './src/index.js'
  },
  output: {
    filename: '[name].js',
    path: path.join(__dirname, 'dist')
  },
  devtool: 'cheap-source-map',
  optimization: {
    minimize: true,
    minimizer: [
      new TerserWebpackPlugin({
        include: /min/,
        sourceMap: true
      })
    ]
  }
}

module.exports = config

关键点如下:

这个时候生成的就完美了。

最后是一个广告贴,最近新开了一个分享技术的公众号,欢迎大家关注?


本篇文章由一文多发平台ArtiPub自动发布

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据