Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
huruji opened this issue Jun 4, 2020 · 0 comments
Open

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

huruji opened this issue Jun 4, 2020 · 0 comments

Comments

@huruji
Copy link
Owner

huruji commented Jun 4, 2020

有的时候我们想要同时生成压缩和未压缩的文件,比如我们构建 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

关键点如下:

image.png

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant